问题很简单:
假设你有一个名为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 string ComplicatedValue {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
在控制器的"创建"操作中
[HttpPost]
public ActionResult Create(Person o, FormCollection collection)
{
// whatever code here;
}
Run Code Online (Sandbox Code Playgroud)
如果你运行它,
我找到了这个问题的原因.
如果将功能更改为
public ActionResult Create(Person o) // Get rid of the *FormCollection collection*
{
// whatever code here;
}
Run Code Online (Sandbox Code Playgroud)
这将消除"潜在的危险"错误.
但我的问题是,对于我的应用程序,我必须在Create Action方法中使用辅助参数FormCollection集合,因为我需要使用一些其他控件值和服务器变量来为ComplicatedValue属性分配计算值.
如果ASP.NET MVC3的任何专家遇到了和我一样的问题,并找到了解决方案,请告诉我.
此链接中的此论坛详细讨论了此问题,并提供了一些解决方法.
http://forums.asp.net/p/1621677/4161637.aspx
以下是该线程的一个解决方案,可能适用于您,也可能不适用于您:
public ActionResult Create(Person o) // Get rid of the *FormCollection collection*
{
FormCollection form = new FormCollection(Request.Unvalidated().Form);
// whatever code here;
}
Run Code Online (Sandbox Code Playgroud)
或者我自己的建议:
public ActionResult Create(Person o, int otherControlValue1, int otherControlValue2, ...)
{
o.ComplicatedValue = CalculateComplicatedValue(otherControlValue1, otherControlValue2, ...);
// whatever code here.
}
Run Code Online (Sandbox Code Playgroud)
在我的情况下,我没有使用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();
}
Run Code Online (Sandbox Code Playgroud)
你有没有尝试过
[绑定(排除=“ComplicatedValue”)]
:
[HttpPost]
public ActionResult Create([Bind(Exclude="ComplicatedValue")]Person o)
{
}
Run Code Online (Sandbox Code Playgroud)
?
这样,它允许您排除在表单上设置ComplicatedValue属性,并且仍然将对象作为Person类提交。
希望有帮助
| 归档时间: |
|
| 查看次数: |
5021 次 |
| 最近记录: |