MVC中Form表单的提交
- 格式:pdf
- 大小:61.27 KB
- 文档页数:2
MVC中Form表单的提交
Web页⾯进⾏Form表单提交是数据提交的⼀种,在MVC中Form表单提交到服务器。服务端接受Form表单的⽅式有多种,如果⼀个Form有2个submit按钮,那后台如
何判断是哪个按钮提交的数据那?
1、采⽤实体Model类型提交
Form表单中的Input标签name要和Model对应的属性保持⼀致,接受Form表单的服务端就可以直接以实体Mode的⽅式存储,这种⽅式采⽤的Model Binder关联⼀起
的。使⽤举例如下。
Web前端Form表单:
数据接收服务端Control⽅法:
public ActionResult SaveEmployee(Employee et)
{
if (ModelState.IsValid)
{
EmployeeBusinessLayer empbal = new EmployeeBusinessLayer();
empbal.SaveEmployee(et);
return RedirectToAction("Index");
}
else
{
return View("CreateEmployee");
}
}
2、⼀个Form有2个submit按钮提交
有时候⼀个Form表单⾥⾯含有多个submit按钮,那么如何这样的数据如何提交到Control中那?此时可以采⽤Action中的⽅法参数名称和Form表单中Input的name名称相
同来解决此问题。举例如下,页⾯既有保存也有取消按钮。
Web前段Form页⾯:
数据接收服务端Control⽅法:通过区分BtnSave值,来⾛不同的业务逻辑
public ActionResult SaveEmployee(Employee et, string BtnSave)
{
switch (BtnSave)
{
case "Save Employee":
if (ModelState.IsValid)
{
EmployeeBusinessLayer empbal = new EmployeeBusinessLayer();
empbal.SaveEmployee(et);
return RedirectToAction("Index");
}
else
{
return View("CreateEmployee");
}
case "Cancel":
// RedirectToAction("index");
return RedirectToAction("Index");
}
return new EmptyResult();
}
3、Control服务端中的⽅法采⽤Request.Form的⽅式获取参数
通过Request.Form获取参数值和传统的⾮MVC接受的数据⽅式相同。举例如下:
public ActionResult SaveEmployee()
{
Employee ev=new Employee();
e.FirstName=Request.From["FName"];
e.LastName=Request.From["LName"];
e.Salary=int.Parse(Request.From["Salary"]);
...........
...........
}
4、MVC中Form提交补充
针对⽅法⼀,我们可以创建⾃定义Model Binder,利⽤⾃定义Model Binder来初始化数据,⾃定义ModelBinder举例如下: