MVC中Form表单的提交

时间:2024-04-03 00:03:59

概述

  Web页面进行Form表单提交是数据提交的一种,在MVC中Form表单提交到服务器。服务端接受Form表单的方式有多种,如果一个Form有2个submit按钮,那后台如何判断是哪个按钮提交的数据那?

MVC中From提交技巧汇总

1、采用实体Model类型提交

  Form表单中的Input标签name要和Model对应的属性保持一致,接受Form表单的服务端就可以直接以实体Mode的方式存储,这种方式采用的Model Binder关联一起的使用举例如下。

  Web前端Form表单:

         <form action="/Employee/SaveEmployee" method="post">
<table>
<tr>
<td>First Name:</td>
<td><input type="text" id="TxtFName" name="FirstName" value="" /></td>
<td>@Html.ValidationMessage("FirstName")</td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" id="TxtLName" name="LastName" value="" /></td>
<td>@Html.ValidationMessage("LastName")</td>
</tr>
<tr>
<td>Salary:</td>
<td><input type="text" id="TxtSalary" name="Salary" value="" /></td>
<td>@Html.ValidationMessage("Salary")</td>
</tr>
<tr>
<td>
<input type="submit" name="BtnSave" value="Save Employee" />
</td>
</tr>
</table>
</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页面:

<form action="/Employee/SaveEmployee" method="post">
<table>
<tr>
<td>First Name:</td>
<td><input type="text" id="TxtFName" name="FirstName" value="" /></td>
<td>@Html.ValidationMessage("FirstName")</td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" id="TxtLName" name="LastName" value="" /></td>
<td>@Html.ValidationMessage("LastName")</td>
</tr>
<tr>
<td>Salary:</td>
<td><input type="text" id="TxtSalary" name="Salary" value="" /></td>
<td>@Html.ValidationMessage("Salary")</td>
</tr>
<tr>
<td>
<input type="submit" name="BtnSaveLearder" value="Save Employee" />
<input type="submit" name="BtnSaveEmployee" value="Cancel" />
</td>
</tr>
</table>
</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举例如下:

MVC中Form表单的提交