c# - ModelState.Clear 不工作

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

我在 MVC 中构建了一个简单的联系表单,它使用 Html 帮助程序类来生成文本框和下拉列表。我想清除文本框和下拉列表的值,就像使用 get 呈现页面时一样(仅在正确提交查询之后)。

我正在使用方法 ModelState.Clear() 来执行此清理,但我的表单值仍然存在,知道我在这里做错了什么吗?成功后,它会在代码中显示消息。您将在下面找到来 self 的 Controller 的代码副本。

感谢您抽出宝贵时间!

[HttpPost]
public ActionResult Contact(ContactUsViewModel model)
{
    if (ModelState.IsValid)
    {
       bool isSuccess = _siteService.CreateInquiry(model.Inquiry);

       if (isSuccess)
       {
           model.SuccessMessage = "Thank you for contacting us.";
           ModelState.Clear();
       }
    }

    model.InquiryTypes = InquiryTypes;
    return View(model);
}

最佳答案

如果成功,只需在 Post-Redirect-Get 之后重定向到您的 GET 操作图案:

public ActionResult Contact()
{
    var model = new ContactUsViewModel
    {
        SuccessMessage = TempData["SuccessMessage"] as string
    };
    return View(model);
}

[HttpPost]
public ActionResult Contact(ContactUsViewModel model)
{
    if (ModelState.IsValid)
    {
       bool isSuccess = _siteService.CreateInquiry(model.Inquiry);
       if (isSuccess)
       {
           TempData["SuccessMessage"] = "Thank you for contacting us.";
           return RedirectToAction("Contact");
       }
    }

    // since you are modifying the value of the InquiryTypes property
    // you need to remove it from the modelstate to avoid getting the 
    // old value rendered by the helpers
    ModelState.Remove("InquiryTypes");
    model.InquiryTypes = InquiryTypes;
    return View(model);
}

或者由于我不是 TempData 的忠实粉丝(因为它使用 Session 并且我个人总是在我的应用程序中禁用它),您可以简单地将查询字符串参数传递给 Contact GET 操作,例如 (success=1 ) 并在此操作中准备成功消息。

关于c# - ModelState.Clear 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9312618/

相关文章:

asp.net-mvc - 如何在单个 Microsoft ASP.NET MVC Web 应用程序中支持个人用户帐户和工作或学校帐户?

c# - 在没有路由或查询字符串参数的 Asp.Net WebApi 操作中使用 FromUri 属性时,是否可以强制实例化复杂类?

asp.net-mvc - MVC 3 中执行流程的差异?

c# - 通过反射设置一个值是行不通的

c# - 如何在控制台应用程序中使用 Actionmailer.Net.Standalone?

asp.net-mvc - 从 MVC Controller 调用 Web API(cookie 身份验证)

c# - SMTP 服务器无法从托管 c# asp.net 发送电子邮件

c# - Principal Role App 引用的属性必须与 EntityType 的键完全相同

c# - 当我运行包含NAudio lib的程序时,出现以下错误,表明(WaveInterop.mmioStringToFOURCC)无法访问

c# - 这个 LINQ 性能从何而来?