我正在尝试学习 MVC3。我已经使用 TextBoxFor HTML 帮助程序控件在多个回发中保留值。
令人惊讶的是,这个值是持久化的,但没有反射(reflect)在 View 中。
我的模型类如下所示:
public class FileViewModel
{
public string FileName { get; set; }
public string ValidationMsg { get; set; }
}
我在 Controller 中的 Actions 方法看起来像这样:
public ActionResult DemoFormElements()
{
return View();
}
[HttpPost]
public ActionResult DemoFormElements(FileViewModel fVM)
{
fVM.FileName = "Overridden Text" + fVM.FileName ;
return View(fVM);
}
我的 View 看起来像这样:
@using (@Html.BeginForm())
{
if (Model != null)
{
@Html.LabelFor(b => b.FileName)
@Html.TextBoxFor(n => n.FileName, Model.FileName)
}
else
{
@Html.LabelFor(b => b.FileName)
@Html.TextBoxFor(n => n.FileName)
}
<input type="submit" id="SubmitBtn" value="Ok" />
}
当我通过单击“确定”按钮回发时,我能够获得我在 文本框,但在 Controller 中,我试图将该值附加到“Hi”并在我的 View 中期望附加值,这没有发生......
我看到控件的值一直存在(无论我输入什么),但没有改变 :( 如果它是预期的行为或者我在这里做错了什么,请帮我提供一些线索?
最佳答案
这有几个问题。您不能在回发期间覆盖模型中的值,因为 MVC 将覆盖它并保留旧值以便在出现错误时重新显示它们。一般来说,您也不应该从 POST 处理程序返回 View ,您应该使用 PRG(发布 - 重定向 - 获取)模式。这样做是为了如果用户在他们的浏览器中单击刷新,它不会再次发布。所以,说了这么多,我会按如下方式更改 Controller :
public ActionResult DemoFormElements()
{
var viewModel = new FileViewModel();
if( TempData.ContainsKey( "UpdatedFilename" )
{
viewModel = TempData["UpdatedFilename"];
}
return View( viewModel );
}
[HttpPost]
public ActionResult DemoFormElements(FileViewModel fVM)
{
TempData["UpdatedFilename"] = "Overridden Text" + fVM.FileName;
return RedirectToAction( "DemoFormElements" );
}
这也将简化您的 View ,因为您不必对模型进行空检查,您将始终拥有一个模型。
@using (@Html.BeginForm())
{
@Html.LabelFor(model => model.FileName)
@Html.TextBoxFor(model => model.FileName)
<input type="submit" id="SubmitBtn" value="Ok" />
}
关于c# - MVC3 : Overriding the Model values in HTTPPost action method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22732672/