这是我的模型,复杂类型类和控制器操作: 正如代码当前所代表的那样, UpdateModel(model)将完全正常,因为我所拥有的模型属性都是简单类型(即 public int number {get; set;} )
此外,我已确认我的输入值已正确发布回服务器并存在于FormCollection中。
我还应该注意,UpdateModel(模型)不会给我带来任何错误以进行故障排除。它所做的只是返回我初始化属性的相同值。因此,我感觉非常困难。
任何想法都会非常感激,此时我的ASP.net MVC 4书缺乏解决这个问题所需的细节。提前致谢! :)
型号
public class HomeModel : BaseModel, IModel
{
public ComplexTypeSchema CTS { get; set; } // <-- this property does not update.
public HomeModel()
{
CTS = new ComplexTypeSchema
{
Property1 = Convert.ToDateTime("1/1/2014"),
Property2 = DateTime.Today,
Property3 = 1.5,
Property4 = ""
};
}
}
复杂类型类
public class ComplexTypeSchema
{
public DateTime Property1 { get; set; }
public DateTime Property2 { get; set; }
public double Property3 { get; set; }
public string Property4 { get; set; }
public int Property5 { get; set; }
public int Property6 { get; set; }
public double Property7 { get; set; }
public ComplexTypeSchema()
{
}
public ComplexTypeSchema Calculate()
{
this.Property5 = (this.Property2 - this.Property1).Days;
this.Property6 = (int)(this.Property5 * this.Property3);
this.Property4 = this.Property1.AddDays(this.Property6).ToShortDateString();
this.Property7 = ((double)this.Property5 / this.Property6) * 100;
return this;
}
}
控制器操作 -
[HttpPost]
public ActionResult Index(FormCollection values)
{
HomeModel model = null;
string viewToReturn = string.Empty;
try
{
model = new HomeModel();
UpdateModel(model.CTS);
}
catch (RulesException e)
{
e.AddExceptionsToModelState(ModelState);
viewToReturn = string.Empty;
}
catch (SystemException e)
{
string message = "Error trying to update model";
ModelState.AddModelError("Error", message);
Log.Error(message, e);
viewToReturn = model.DefaultViewForError;
}
return View(viewToReturn, model);
}
答案 0 :(得分:0)
为什么不将model.CTS传递给UpdateModel()?
try
{
model = new HomeModel();
UpdateModel(model.CTS); <-----
}
另外,最后是否应该有一个()?
public HomeModel()
{
CTS = new ComplexTypeSchema() <-------
{
........
答案 1 :(得分:0)
您的CTS对象是另一个对象的属性。因此模型绑定器将寻找名为CTS的属性,然后尝试绑定内部的poperties。在表单集合中,您应该看到类似“CTS.Property1”
的内容所以你应该传入你的enitre模型,而不仅仅是CTS对象。当然这取决于你的观点是什么......
如果你只想绑定一个CTS对象,而不是更新模型的其余部分,你可以使用类似的东西欺骗模型绑定器:
var foolme = new { CTS = myCtsObjevt } ;
UpdateModel(foolme)
答案 2 :(得分:0)
只是概念证明 Controler.UpdateModel将无法正常工作。