Action方法,以强类型的方式接收表单数据
第一种方法:通过FormCollection类型的Action方法参数来接受全部表单数据,而后使用UpdateModel()把表单数据写入强类型实例。
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection formValues)
{
Dinners dinners = dinnerRepository.GetDinners(id);
try
{
UpdateModel(dinners);
dinnerRepository.Save();
return RedirectToAction("Details", new { id = dinners.DinnerID });
}
catch
{
ModelState.AddRuleViolations(dinners.GetRuleViolations());
return View(dinners);
}
}
第二种方法:直接使用一个强类型作为Action方法的参数来把表单数据写入强类型参数变量中。
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Dinners dinners)
{
if (ModelState.IsValid)
{
try
{
dinners.HostedBy = "SomeUser";
dinnerRepository.Add(dinners);
dinnerRepository.Save();
return RedirectToAction("Details", new { id = dinners.DinnerID });
}
catch
{
ModelState.AddRuleViolations(dinners.GetRuleViolations());
}
}
return View(dinners);
}
默认情况下,第一种情况UpdateModel()方法试图把所有表单项都匹配到强类型的属性。第二种情况也是如此,会自动试图把所有表单项全部都应赋值给强类型参数变量。
但是有时,我们可能只想或者表单项中只有一部分数据能都应赋值给强类型属性集。
在表单数据被映射使用的地方作出限定
使用UpdateMode时:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection formValues)
{
Dinners dinners = dinnerRepository.GetDinners(id);
//指定模型对象可更新的属性列表
String[] allowPropery = new[] { "Title", "Description", "ContactPhone" };
try
{
//使用UpdateModel重载方法
UpdateModel(dinners,allowPropery);
dinnerRepository.Save();
return RedirectToAction("Details", new { id = dinners.DinnerID });
}
catch
{
ModelState.AddRuleViolations(dinners.GetRuleViolations());
return View(dinners);
}
}
Action参数为强类型时:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Include="Title,Description,ContactPhone")]Dinners dinners)
{
if (ModelState.IsValid)
{
try
{
//没有通过表单赋值的属性,可以手动赋值
dinners.HostedBy = "SomeUser";
dinnerRepository.Add(dinners);
dinnerRepository.Save();
return RedirectToAction("Details", new { id = dinners.DinnerID });
}
catch
{
ModelState.AddRuleViolations(dinners.GetRuleViolations());
}
}
return View(dinners);
}
-
直接在类的定义时,作出限定s
通过添加[Bind]属性到类上,或者在应用程序中的Global.asax文件中(如果类型不是我们自定义的情况下,非常有用),使用Bind属性的Include和Exclude属性来指定类或接口中的那些属性是可以绑定的。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Linq;
namespace NerdDinner.Models
{
[System.Web.Mvc.Bind(Include="Title,Description,ContactPhone")]
public partial class Dinners
{
}
}