我使用UserSample模型查看了两个属性(用户名,密码),我想要实现的是从文本框中获取这些值并将它们存储到对象模型中,然后在Action方法中获取此对象和操纵它。
但是在这段代码中,在提交带有填充文本框字段的表单后,操作方法Index中的对象属性始终为null。
控制器:
public ActionResult Index(UserSample user) //this is the object which properties I want to be asigned.
{
if (user != null)
{
}
return View();
}
查看:
@using (@Html.BeginForm("Index","Login"))
{
<table>
<tr>
<td>Username: </td>
<td>@Html.TextBox("Username")</td>
</tr>
<tr>
<td>Password: </td>
<td>@Html.TextBox("Password")</td>
</tr>
<tr>
<td></td>
<td><input id="btnSubmit" type="submit" value="Submit" /></td>
</tr>
</table>
}
答案 0 :(得分:2)
尝试将此行添加到您的视图中:
@model UserSample
您可能需要在那里包含命名空间。例如MyApp.Models.UserSample
。
然后你可以使用stronly类型的html-helpers:
<td>@Html.TextBoxFor(model => model.UserName)</td>
和
<td>@Html.TextBoxFor(model => model.Password)</td>
您应该使用Index(UserSample user)
属性装饰HttpPost
方法:
public ActionResult Index()
{
// Get method.
UserSample model = new UserSample();
return View(model);
}
[HttpPost]
public ActionResult Index(UserSample user)
{
// POST method.
}
现在发布表单时,应使用表单中的值填充UserSample
对象。
如果您不了解模型绑定,我建议您调查一下。 This tutorial可能会让你开始。