c# - MVC3 : Overriding the Model values in HTTPPost action method

标签 c# asp.net-mvc asp.net-mvc-3 razor

我正在尝试学习 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/

相关文章:

c# - 文件关联导致 Clickonce 安装失败

c# - 我可以在 UWP 上运行一些 http 服务器吗?

c# - 虚拟化堆栈面板返回空选定项

c# - 如何在 ASP.Net MVC 5 应用程序中从浏览器获取 URL

asp.net-mvc - 使用 ValueInjecter 在具有不同属性名称的对象之间进行映射

c# - 遍历 DirectoryEntry 或任何对象层次结构 - C#

asp.net-mvc - 我的 ASP.NET MVC 应用程序是否需要 "Administrator"区域?

asp.net-mvc - 反序列化 JSON 时 MVC3 RTM 失败数字类型强制

c# - 使用 JS 函数调用的 MVC3 中的分页问题

asp.net-mvc - RavenDb - 远程服务器返回错误 : (403) Forbidden