[英]System.ArgumentNullException occured in System.Web.Mvc.dll
我有一個應用程序,我需要在其中輸入數據,並在提交時將數據保存在數據庫中。 當我在數據庫中簽入時,輸入已成功保存,但是在httppost后重新加載頁面時出現了異常。 我在遇到異常情況:
@Html.DropDownList("LineID", new SelectList(Model.dropConfig, "LineID", "LineID"), "-- Select LineID --", new { required = true, @class = "form-control" })
控制器代碼以獲取下拉列表值,並與Db綁定:
[ActionName("DetailsForm")]
[HttpGet]
public ActionResult DetailsForm()
{
try
{
var model = new DetailsViewModel() { dropConfig = floorService.DropDownList().ToList() };
return View("DetailsForm", model);
}
catch (Exception ex)
{
return View("_error");
}
}
控制器代碼到http發布:
[ActionName("DetailsForm")]
[HttpPost]
public ActionResult DetailsForm(DetailsViewModel model, FormCollection form)
{
DetailsConfiguration detailsConfig = new DetailsConfiguration();
detailsConfig.LineID = Convert.ToString(form["LineID"]);
//Similary for other fields
floorService.SaveDetails(detailsConfig);
ModelState.Clear();
ViewBag.message = "Success";
return View("DetailsForm",model);
}
因為您的視圖代碼使用Model.dropConfig
來構建下拉列表的SelectList
,並且您沒有在返回視圖之前設置dropConfig
屬性值。
記住, Http是無狀態的 。 因此,即使您在GET操作中設置了dropConfig屬性值,它也無法在HttpPost操作中使用。 提交表單時,這是對服務器的全新請求。
您可以通過再次加載dropConfig
屬性來修復它。
model.dropConfig = floorService.DropDownList().ToList();
return View(model);
但是理想情況下,您應該遵循PRG模式 。
PRG代表Post - Redirect - Get 。 因此,當您將表單提交到http post操作方法時,您應該返回重定向響應,瀏覽器將對該操作方法進行新的GET調用。
您可以使用RedirectToAction
方法返回重定向響應。
floorService.SaveDetails(detailsConfig);
return RedirectToAction("DetailsForm");
這會將302響應發送回瀏覽器,並將位置標頭設置為DetailsForm
操作方法的url,瀏覽器將對此發出新的GET請求。
使用重定向響應時,ViewBag無法使用。 因此,您可以考慮使用TempData。 TempData可用於在兩個請求之間進行傳輸。
TempData["message"] = "Success";
return RedirectToAction("DetailsForm");
現在,您可以在DetailsForm操作方法或該方法呈現的視圖中讀取TempData["message"]
。
例如,您可以像這樣在視圖(由DetailsForm GET操作方法呈現)中讀取它
@if (TempData["message"]!=null)
{
<div class="alert alert-success" id="alert">
<button type="button" class="close" data-dismiss="alert">x</button>
<strong>Success! </strong>@TempData["message"]
</div>
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.