简体   繁体   English

MVC传递模型来查看

[英]MVC pass model to view

My Index.cshtml 我的Index.cshtml

@model ReportGenerator.WebUI.Models.ReportViewModel
@Html.TextBoxFor(m => m.report.FileName, new { @class = "form-control", id = "FileName" })

My controller 我的控制器

public ActionResult Index(ReportViewModel model)
{
    ...some stuff
    model.report = new Report();
    model.report.FileName = "INDEX";
    return View(model);
}

public ActionResult fillFields(ReportViewModel _model)
{
    ...some stuff
    _model.report = new Report();
    _model.report.FileName = "FILL";
    return View("Index", _model);
}

When I run my application the TextBox Text property is set to "INDEX". 当我运行我的应用程序时, TextBox Text属性设置为“INDEX”。 Also when I click on a button which calls the fillFields controller action, the TextBox is still displaying "INDEX", it's not changing to "FILL". 此外,当我单击调用fillFields控制器操作的按钮时, TextBox仍然显示“INDEX”,它不会更改为“FILL”。

What am I doing wrong? 我究竟做错了什么? Why it doesn't want to work? 为什么不想工作?

@StephenMuecke answered this correctly in the comments above. @StephenMuecke在上面的评论中正确回答了这个问题。

Your not doing anything wrong. 你没有做错什么。 Your fillFields() method has a parameter ReportViewModel so its values are added to ModelState when the method is initialized. fillFields()方法有一个参数ReportViewModel,因此在初始化方法时将其值添加到ModelState。 When you return the view, your TextBoxFor() method uses the value from ModelState (not the model property) to set the value of the textbox. 返回视图时, TextBoxFor()方法使用ModelState的值(而不是model属性)来设置文本框的值。 The reason for this is explained here . 这里解释其原因。 The correct approach is to follow the PRG pattern – 正确的方法是遵循PRG模式 -

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM