当我使用下面的代码时,我得到的空引用没有设置为mvc4中的对象实例。我使用FormCollection方法将日期作为输入传递。当我追踪时,它显示sd的空值(sd是startdate变量)。如何解决此异常?
控制器:
[HttpPost]
public ActionResult Index(FormCollection formCollection)
{
List<tblGroup> allg = new List<tblGroup>();
using (portalconnectionstring con = new portalconnectionstring())
{
allg = con.grt.OrderBy(m => m.groupname).ToList();
}
ViewBag.disg = new SelectList(allg, "groupid", "groupname");
var sd = formCollection["txtDate"]; //Showing null value here while i traced out
var ed = formCollection["Txtenddate"];
....
.....
}
查看:
@using (Html.BeginForm("Index","MyController",FormMethod.Post,new {id="form1"}))
{
<div>
@Html.Label(" ",new { id ="Label1" })
<input id="txtDate" type="text" value="Startdate: "/>
<div>
<input id="Txtenddate" type="text" value="Enddate: "/>
</div>
<div>
@Html.Label("Group Name", new{id="lblGroupName"})
</div>
<div>
@Html.DropDownListFor(model => model.groupid, @ViewBag.disg as SelectList, "select")
@Html.ValidationMessageFor(model=>model.groupid)
</div>
<input type="submit" id="Button1" Value="Submit"/>
</div>
}
答案 0 :(得分:2)
您需要为输入提供name
属性
<input id="txtDate" name="txtDate" type="text" value="Startdate: "/>
但是,如果您使用html帮助程序绑定到模型属性(例如@Html.TextBoxFor(m => m.txtDate)
),这将自动完成,在这种情况下,您可以在POSt方法中绑定回模型,而不是使用{{1 }}