C# System.Web.Mvc.dll中发生System.ArgumentNullException异常
我有一个应用程序,我需要输入数据,并在提交数据保存在数据库中。当我签入数据库时,输入被成功保存,但当页面在httppost之后重新加载时,我得到一个异常。 我在以下方面遇到了例外:C# System.Web.Mvc.dll中发生System.ArgumentNullException异常,c#,asp.net-mvc,C#,Asp.net Mvc,我有一个应用程序,我需要输入数据,并在提交数据保存在数据库中。当我签入数据库时,输入被成功保存,但当页面在httppost之后重新加载时,我得到一个异常。 我在以下方面遇到了例外: @Html.DropDownList("LineID", new SelectList(Model.dropConfig, "LineID", "LineID"), "-- Select LineID --", new { required = true, @class = "form-control" })
@Html.DropDownList("LineID", new SelectList(Model.dropConfig, "LineID", "LineID"), "-- Select LineID --", new { required = true, @class = "form-control" })
获取dropdownlist值的控制器代码,与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 post的控制器代码:
[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);
但理想情况下,您应该遵循
p-R-G代表发布-重定向-获取。因此,当您将表单提交给http post操作方法时,应该返回重定向响应,浏览器将对该操作方法进行新的GET调用
您可以使用RedirectToAction
方法返回重定向响应
floorService.SaveDetails(detailsConfig);
return RedirectToAction("DetailsForm");
这将向浏览器发送一个302响应,并将位置头设置为DetailsForm
操作方法的url,浏览器将对此发出一个新的GET请求
使用重定向响应时,ViewBag将不工作。所以你可以考虑使用TimDATA。TempData可用于在两个请求之间传输
TempData["message"] = "Success";
return RedirectToAction("DetailsForm");
现在,您可以在DetailsForm操作方法或该方法呈现的视图中读取TempData[“message”]
例如,您可以在视图中读取它(由DetailsForm GET action方法呈现),如下所示
@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>
}
@if(TempData[“message”!=null)
{
x
成功!@TempData[“消息”]
}
我尝试了返回重定向到操作(“DetailsForm”)代码>并且工作正常:)但是TempData仍然没有为我显示成功消息。如果您访问TempData[“message”]
,它应该可以工作。它应该只适用于下一个请求。你是怎么读的?我曾经像你提到的TempData[“message”]=“Success”代码>这就是设置它的方式。你读回去有困难吗?你是如何在DetailsForm中阅读它的?我已经在DetailsForm@if(!string.IsNullOrEmpty(ViewBag.message))中添加了这个{x成功!成功提交请求表单。}
我使用TempData[“message”]代替Viewbag.messgae。它会引发一个错误。