【发布时间】:2016-09-12 22:54:41
【问题描述】:
这是我的模型、复杂类型类和控制器操作: 就目前的代码而言,UpdateModel(model) 当我拥有的所有模型属性都是简单类型时(即 public int number {get; set;})将工作得非常好.
此外,我已确认我的输入值已正确回传到服务器并存在于 FormCollection 中。
我还应该注意,UpdateModel(model) 不会抛出任何错误让我进行故障排除。它所做的只是返回与我初始化属性相同的值。因此,我感觉很困。
任何想法都将不胜感激,此时我的 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);
}
【问题讨论】:
-
您只是创建了一个新的 HomeModel 对象,然后保存了它的更改,但是没有代码将表单发布值与您正在创建的新模型相关联,或者您是否省略了该代码?跨度>
-
我同意@3dd。您的代码对传递给它的 FormCollection 没有任何作用。这是故意的吗?此外,如果 HomeModel() 是您在视图中使用的模型,那么您很可能会收到 HomeModel() 作为 Index() 中的参数。
-
我在我的 asp.net mvc 书中读到“默认情况下,默认模型绑定器在四个位置搜索与被绑定参数名称匹配的数据。(1.Request.Form, 2. RouteData.Values、3.Request.QueryString 和 4.Request.Files)”。我所拥有的是我希望我如何设置此操作结果,我省略了我如何使用更新的模型值。
-
那么 model.ComplexTypeSchema 不是 HomeModel 的属性,但我确信它只是被省略了。为什么您不只是将 HomeModel 传递到操作方法并坚持下去的任何充分理由。
-
如何为
HomeModel.CTS属性生成html?
标签: c# asp.net-mvc