MVC 4 - 来自控制器的错误消息未在视图中显示

时间:2015-03-24 22:17:07

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

我有一个MVC网站,当一个字段失去焦点时,它将读取后端数据库并确定该值是否有效。如果该值有效,则将填充页面上的其他两个字段。我遇到的问题是当值无效并且我想在文本框下显示错误消息时就像验证消息一样。

观点......

@Html.ValidationSummary(true)    
<div class="form-group">
    @Html.LabelFor(m => m.HSDRepCode)
    @Html.TextBoxFor(m => m.HSDRepCode, new { placeholder = "Enter your HSD Rep code...", @class = "contact-name" })
    @Html.ValidationMessageFor(m => m.HSDRepCode)
</div>

调用脚本......

$("#HSDRepCode").blur(function () {
        $.ajax({
            url: "/CRM/ValidateHSDRep",
            type: "POST",
            data: $('form').serialize(),
            dataType: "json"
        }).done(function (model) {
            $("#HSDRepCode").val(model.HSDRepCode);
            $("#HSFirstName").val(model.HSFirstName);
            $("#HSLastName").val(model.HSLastName);
        });
    });

模特......

public class LeadInfo
{
    [Display(Name = "Products of Interest")]
    [Required(ErrorMessage = "Please select a product of interest")]
    public string Product { get; set; }

    [Display(Name = "HSD Rep code")]
    [Required(ErrorMessage = "Please enter your HSD Rep code")]
    [StringLength(6)]
    public string HSDRepCode { get; set; }

    [Display(Name = "HSD Rep first name")]
    [Required(ErrorMessage = "Please enter your first name")]
    public string HSFirstName { get; set; }

    [Display(Name = "HSD Rep last name")]
    [Required(ErrorMessage = "Please enter your last name")]
    public string HSLastName { get; set; }

    [Display(Name = "Doctor's first name")]
    [Required(ErrorMessage = "Please enter the doctor's first name")]
    public string FirstName { get; set; }

    [Display(Name = "Doctor's last name")]
    [Required(ErrorMessage = "Please enter the doctor's last nname")]
    public string LastName { get; set; }

    [Display(Name = "Doctor's phone number")]
    [Required(ErrorMessage = "Please enter the doctor's phone number")]
    [Phone]
    public string PhoneNumber { get; set; }

    [Display(Name = "Doctor's e-mail")]
    [Required(ErrorMessage = "Please enter the doctor's e-mail")]
    [EmailAddress]
    public string EmailAddress { get; set; }
}

和控制器......

public ActionResult ValidateHSDRep(LeadInfo leadInfo)
{
    HSDRep hsdRep = new HSDRep();

    hsdRep = CRMModels.ValidateHSDRepCode(leadInfo.HSDRepCode);

    if (hsdRep.FirstName != null)
    {
        leadInfo.HSFirstName = hsdRep.FirstName;
        leadInfo.HSLastName = hsdRep.LastName;

        return Json(leadInfo);
    }
    else
    {
        ModelState.AddModelError("HSDRepCode", "Invalid HS Representative Code");

        return Json(leadInfo);
    }
}

当文本框失去焦点时,将调用控制器例程。

如何显示消息&#34;无效的代表代码&#34;在文本框&#34; HSDRepCode&#34;?

谢谢, 加里

更新:我添加了调用控制器功能的Ajax代码。 更新2:我更改了返回以返回Json。

2 个答案:

答案 0 :(得分:2)

您的ValidateHSDRep()方法返回的json没有模型状态的概念。此外,通过将整个模型发送到视图,然后在仅需要发送一个属性并返回两个属性时再将其全部发送回来,会不必要地降低性能。将脚本更改为仅发送HSDRepCode值,并仅返回所需内容

var url = '@Url.Action("ValidateHSDRep", "CRM");
$("#HSDRepCode").blur(function () {
  $.getJSON(url, { HSDRepCode: $(this).val() }, function(response) {
    if (response.ErrorMessage) {
      // do something with the error message
    } else {
      $("#HSFirstName").val(response.HSFirstName);
      $("#HSLastName").val(response.HSLastName);
      // remove any associated error message that may have been added in previous calls
    }
  });
});

并将控制器方法更改为

public ActionResult ValidateHSDRep(string hSDRepCode)
{
  HSDRep hsdRep = CRMModels.ValidateHSDRepCode(hSDRepCode);
  if (hsdRep.FirstName == null)
  {
    return Json(new { ErrorMessage = "Invalid HS Representative Code" }, JsonRequestBehavior.AllowGet);
  }
  else
  {
    return Json(new { HSFirstName = hsdRep.FirstName, HSLastName = hsdRep.LastName; }, JsonRequestBehavior.AllowGet);
  }
}

但是,由于您在视图中包含@Html.ValidationMessageFor(m => m.HSDRepCode),因此您可以使用模型属性上的RemoteAttribute来处理“无效代码”

[Display(Name = "HSD Rep code")]
[Required(ErrorMessage = "Please enter your HSD Rep code")]
[StringLength(6)]
[Remote("IsHSDRepCodeValid", "CRM", ErrorMessage = "Invalid HS Representative Code")]
public string HSDRepCode { get; set; }

然后添加控制器方法

public JsonResult IsHSDRepCodeValid(string HSDRepCode)
{
  // code to test if valid
  if(isValid)
  {
    return Json(true, JsonRequestBehavior.AllowGet)
  }
  else
  {
    return Json(false, JsonRequestBehavior.AllowGet) // displays default message defined in ErrorMessage property
    // or
    return Json("a custom message", JsonRequestBehavior.AllowGet)
  }
}

有关使用远程验证的更多详细信息,请参阅How to: Implement Remote Validation in ASP.NET MVC

答案 1 :(得分:-1)

.AddModelError方法的第一个参数是key,在您的情况下是HSDRepCode,而不是hsdrepcode

所以:

ModelState.AddModelError("HSDRepCode", "Invalid Representative Code");

它有效吗?感谢