若要实现强类型视图中提交表单,把View中的Model数据传递给Control,那么必须要确保一件事——表单中的input标签元素的name属性的值必须与model中的属性名相同,不区分大小写。
示例代码如下:
view视图代码
@model MVCCase.Models.EditModels <h2>Edit</h2> <form action="/home/edit" method="post"> <fieldset> <legend>EditModels</legend> <div class="editor-label"> 姓名 </div> <div class="editor-field"> <input type="text" name="name" /> </div> <div class="editor-label"> 性别 </div> <div class="editor-field"> <input type="text" name="gender" /> </div> <div class="editor-label"> 年龄 </div> <div class="editor-field"> <input type="text" name="age" /> </div> <p> <input type="submit" value="Save" /> </p> </fieldset> </form>
注:这里表单提交使用了post方式,以get方式也是没有问题的。
控制器代码
public class HomeController : Controller { public ActionResult Index() { ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application."; return View(); } public ActionResult Edit(EditModels model) { Response.Write(model.Name + " " + model.Age + " " + model.Gender); return View(); } }注:这里只是验证数据有没有传到后端。
model代码
public class EditModels { public string Name { get; set; } public string Gender { get; set; } public string Age { get; set; } }
另,B/S应用程序,如客户端使用:ExtJs和JqueryUI等 ,可以使用FormCollection接收客户端数据,代码如下
view中代码
@{ Layout = null; } <!DOCTYPE html> <html> <head> <title>用户编辑</title> </head> <body> @using (@Html.BeginForm()) { <div> 用户名:@Html.TextBox("UserName", null, new { @style = "200px" }) </div> <div> 密码:@Html.Password("Password") </div> <div> <input type="submit" value="提交" /></div> } </body> </html>
控制器中代码
//UserEdit public ActionResult UserEdit_01() { return View(); } [HttpPost]//UserEdit public ActionResult UserEdit_01(FormCollection form) { Response.Write(form["UserName"]); Response.Write("<br />"); Response.Write(form[1]); Response.Write("<br />"); return View(); }