MVC 4 Razor。部分视图表单验证

时间:2013-10-12 18:56:43

标签: asp.net asp.net-mvc-4

我的索引页面上有部分视图 EnquiryForm ,我正在尝试从部分视图发布数据。

 [HttpPost]
 public ActionResult EnquiryForm(Booking model)
 {
    if (ModelState.IsValid)
    {
       ........
    }
    return RedirectToAction("Index", "Home");
 }

发布表单时,空白验证无效,服务器端验证

预订模式

public class Booking
{
    [Required(ErrorMessage = " - Required" )]
    public string Name { get; set; }

    [Required(ErrorMessage = " - Required")]
    [RegularExpression(".+@.+\\..+", ErrorMessage = "In-Correct Email")]
    public string Email { get; set; }
}

此致 感谢

1 个答案:

答案 0 :(得分:0)

如果验证为false并且您将页面重定向到“/ Home / Index”,则不会看到验证消息。见打击:

[HttpPost]
 public ActionResult EnquiryForm(Booking model)
 {
    if (ModelState.IsValid)
    {
       ........ 
    }
  //  return RedirectToAction("Index", "Home"); 
      return View();
 }

或者您可以尝试以下代码:

您的控制器

[HttpGet]
public ActionResult EnquiryForm()
{          
     return View();
}

[HttpPost]
public ActionResult EnquiryForm(Booking model)
{
   if (ModelState.IsValid)
    {
        return RedirectToAction("Index", "Home");
    }
   return View();
}

您的EnquiryForm查看

@using (Html.BeginForm("EnquiryForm", "Home", FormMethod.Post))
{       
   @Html.Partial("_EnquiryFormPartialView", Model)

   <input type="submit" id="bt_submit"/>
 }

您的意见

<div>
    @Html.LabelFor(n => n.Name)
    @Html.TextBoxFor(n => n.Name)
    @Html.ValidationMessageFor(n => n.Name)
</div>

<div>
  @Html.LabelFor(n => n.Email)
  @Html.TextBoxFor(n => n.Email)
  @Html.ValidationMessageFor(n => n.Email)
</div>