0

這是包含上傳文件控件的View。所以它需要「multipart/form-data」內容類型。設置enctype =「multipart/form-data」會導致所有ViewBags值丟失

@using (Html.BeginForm("Create", "RoutinTest", FormMethod.Post, 
new { enctype = "multipart/form-data" })) 
{ 
    @Html.AntiForgeryToken() 

<div> 
      @Html.LabelFor(model => model.ScannedFile) 
      <div> 
       <input type="file" name="ScannedFile" multiple="multiple" /> 
       @Html.ValidationMessageFor(model => model.ScannedFile) 
      </div> 
</div> 
<div> 
      <div> 
       <input type="submit" value="Save" /> 
      </div> 
</div> 

這是我的控制器,它的創建操作方法:

[HttpGet] 
public ActionResult Create(string patientId, string fullName) 
     { 
      ViewBag.PatientId = patientId; 
      ViewBag.FullName = fullName; 
      return View(); 
     } 

[HttpPost] 
public ActionResult Create() RoutinTest routintest, string patientId, string fullName) 
{ 

} 

的問題是,在第二個Create action方法(POST方法)都patientId和全名都將丟失。 (patientId = 0和fullName = null),但我將它們都設置爲Get方法。令人驚訝的是,當我將表單內容類型更改爲默認值(通過刪除multipart/form-data),我可以獲得這兩個參數值。我知道我可以通過將這兩個ViewBags值設置爲隱藏字段而不更改表單內容類型來解決問題,但我只想知道爲什麼會發生這種情況?什麼影響「multiPart/form-data」表單內容類型對這些ViewBags值有影響?

感謝

回答

1

記住,你的patientIdfullName在URL中找到。他們重新分配到ViewBag沒有什麼用它做(除去ViewBag看看會發生什麼)

// Looks familliar? This is your first request. 
Create?patientId=0&fullName= 

默認情況下,傳遞到第二Create操作方法,因爲URL參數維護的參數。

// By default, parameters are not cleared during the second request. 
Create?patientId=0&fullName= 

當您設置enctype = "multipart/form-data",在URL參數被清除,導致這樣的事情。

Create 

這意味着它是丟失的參數而不是ViewBag數據。

相關問題:Form Post with enctype = "multipart/form-data" causing parameters to not get passed

+0

約羅:非常感謝。您能否告訴我是否有任何其他方式來檢索URL參數,而不是使用以下方式:Request.Params [「fullName」] –

相關問題