即使表单有错误,ViewBag消息也会更改

时间:2015-03-18 20:29:52

标签: asp.net-mvc validation

我有一个简单的联系表单,它正在使用模型的字段,一切似乎都有效,但无论是否存在验证错误,ViewBag消息都会发生变化,用户验证会阻止此但我还需要HttpPost操作来设置基于表单是否填写正确的消息。

我尝试使用 if(ModelState.IsValid),但它似乎不起作用。我意识到我可以手动检查主页中的每个变量,看看它是否为空,但这并不能真正告诉我它是否有效或者是否有错误返回的帖子,是否有针对此的构建方法?

ContactFormModel.cs

namespace TestApplication.Models
{
    public class ContactFormModel
    {
        [Required]
        [Display(Name = "Name")]
        public string name { get; set; }

        [Required]
        [Display(Name = "Phone")]
        public string phone { get; set; }

        [Required]
        [Display(Name = "Message")]
        public string message { get; set; }
    }
}

HomeController.cs

[HttpPost]
public ActionResult Contact(ContactFormModel contactForm)
{
     ViewBag.Message = "Thank you. Your message has been sent.";
     return View();
}

Contact.cshtml

@model TestApplication.Models.ContactFormModel
@{
    ViewBag.Title = "Contact";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>

<p>Use this area to provide additional information.</p>

@*@if (!IsPost)
{
    @Html.EditorForModel(Model)
}*@

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.LabelFor(model => model.name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.name, "", new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.phone, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.phone, "", new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.phone, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.message, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextAreaFor(model => model.message, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.message, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>


    </div>
}

1 个答案:

答案 0 :(得分:0)

执行所需操作的模式是检查ModelState.IsValid。如果它是有效的继续处理,如果没有返回包含现有模型内容的视图,则给予用户纠正错误的机会。

[HttpPost]
public ActionResult Contact(ContactFormModel contactForm)
{
    if (ModelState.IsValid)
    {
        ViewBag.Message = "Thank you. Your message has been sent.";
        return View();
    }
    else
    {
        return View(contactForm);
    }
}

话虽如此,您应该考虑使用PRG(重定向后获取)模式。通过在方法的HttpPost版本中返回相同的视图,您可以重复发布数据。如果用户在浏览器中点击“刷新”,它将重新发布他们刚刚发布的数据(在弹出一个大多数非技术用户永远不会理解的对话框之后)。您必须拥有一个HttpGet版本,该版本首先提供视图,您应该在成功时重定向到该版本。您必须切换为使用TempData而不是ViewBag,因为ViewBag无法在重定向后继续使用。

[HttpPost]
public ActionResult Contact(ContactFormModel contactForm)
{
    if (ModelState.IsValid)
    {
        TempData.Message = "Thank you. Your message has been sent.";

        // Assumes there is a Get version of the Contact action method
        return RedirectToAction("Contact");
    }
    else
    {
        return View(contactForm);
    }
}