Asp.net mvc 3 MVC ASP.NET MVC3 AllowHtml属性不工作?
问题很简单: 假设你有一个叫Person的模特Asp.net mvc 3 MVC ASP.NET MVC3 AllowHtml属性不工作?,asp.net-mvc-3,Asp.net Mvc 3,问题很简单: 假设你有一个叫Person的模特 public class Person { public int PersonID {get; set;} public string Name {get; set;} [AllowHtml] // Allow html in Intro property public string Intro {get; set;} [ScaffoldColumn(false)]
public class Person
{
public int PersonID {get; set;}
public string Name {get; set;}
[AllowHtml] // Allow html in Intro property
public string Intro {get; set;}
[ScaffoldColumn(false)]
public string ComplicatedValue {get; set;}
}
在控制器的创建操作中
[HttpPost]
public ActionResult Create(Person o, FormCollection collection)
{
// whatever code here;
}
如果你运行它
public ActionResult Create(Person o) // Get rid of the *FormCollection collection*
{
// whatever code here;
}
这将消除“潜在危险”错误
但我的问题是,对于我的应用程序,我必须在Create Action方法中使用次要参数FormCollection collection,因为我需要使用一些其他控制值和服务器变量来将计算值分配给compleddvalue属性
如果ASP.NET MVC3的任何专家遇到了与我相同的问题,并找到了解决方案,请告诉我 你试过了吗
[绑定(排除=“复杂值”)]
:
?
这样,您就可以排除表单上的设置复杂值属性,并且仍然将对象作为个人类提交
希望对您有所帮助。我建议您使用自定义模型绑定器,而不是从FormCollection中提取复杂的数据。Scott Hanselman发表了一篇关于创建自定义模型绑定器的文章,该绑定器可以作为一个好的模板。在他的帖子中,他整合了一个DateTimeModelBinder,它允许通过一个包含日期的输入或一对包含日期和时间的输入来设置DateTime属性。这个论坛在这个链接上详细讨论了这个问题,并给出了一些解决方法 以下是该线程的一个解决方案,可能对您有效,也可能对您无效:
public ActionResult Create(Person o) // Get rid of the *FormCollection collection*
{
FormCollection form = new FormCollection(Request.Unvalidated().Form);
// whatever code here;
}
或者我自己的建议:
public ActionResult Create(Person o, int otherControlValue1, int otherControlValue2, ...)
{
o.ComplicatedValue = CalculateComplicatedValue(otherControlValue1, otherControlValue2, ...);
// whatever code here.
}
在我的例子中,我没有使用FormCollection,但它在那里,因此我在[HttpPost]方法上有一个不同的足迹。我做了这个黑客并输入了一个伪造的参数:
public virtual ActionResult Edit(int id)
{
return View(this.repository.GetById(id));
}
[HttpPost]
public virtual ActionResult Edit(int id, int? bogusID)
{
var d = repository.GetById(id);
if (TryUpdateModel(d))
{
repository.Save();
return RedirectToAction("Index");
}
return View();
}
实际上,这排除了o.ComplementdValue属性,但它仍保留在FormCollection中,因此仍然会触发错误。答案帮助我们解决了这个问题。多谢!上面的例子对我很有用,除了我必须从
Request.Unvalidated().Form
中删除额外的()
,只需使用Request.Unvalidated.Form
而不是伪参数,只需执行不同的函数名(例如更新(int-id)),并用属性ActionName(“编辑”)进行标记。
public virtual ActionResult Edit(int id)
{
return View(this.repository.GetById(id));
}
[HttpPost]
public virtual ActionResult Edit(int id, int? bogusID)
{
var d = repository.GetById(id);
if (TryUpdateModel(d))
{
repository.Save();
return RedirectToAction("Index");
}
return View();
}