MVC3中的远程验证属性无效获取格式

时间:2012-10-08 12:14:35

标签: asp.net-mvc-3 remote-validation

我第一次尝试使用远程验证,但遇到了远程验证方法传递的参数问题。

我的模型如下:

public class PerinatalWomanView : IPerinatalWoman
{
[Required(ErrorMessage = "The woman's postcode is required")]
    [Display(Name = "Woman's postcode")]
    [Remote("PostcodeCheck", "Validation", "Validation")]
    [RegularExpression("^[a-zA-Z]{1,2}[0-9][0-9A-Za-z]{0,1} [0-9][A-Za-z]{2}$", ErrorMessage = "A valid postcode is required")]
    public string Postcode { get; set; }

视图片段是:

<div class="editor-label control-label">
  @Html.LabelFor(m => m.perinatalWomanView.Postcode)
</div>
div class="editor-field controls">
  @Html.EditorFor(m => m.perinatalWomanView.Postcode)
  @Html.ValidationMessageFor(m => m.perinatalWomanView.Postcode)
</div>

并且验证控制器是:

public class ValidationController : Controller
{
    //
    // GET: /Validation/Validation/

    [HttpGet]
    public JsonResult PostcodeCheck(string Postcode)
    {

        //  postcode has already been checked for correct format
        //  now look it up to see if it exists

        string mbrraceCommonCodeEntitiesConnectionString = ConfigurationManager.ConnectionStrings["MbrraceCommonCodeEntities"].ConnectionString;
        if (PostcodeChecks.CheckPostcodeExists(mbrraceCommonCodeEntitiesConnectionString, Postcode))
        { return Json(true, JsonRequestBehavior.AllowGet); }

        return Json("This postcode was not found in the database", JsonRequestBehavior.AllowGet);

    }

调用控制器时,Postcode的值为null。来自Firebug的实际电话是:

http://localhost:57881/Validation/Validation /PostcodeCheck?perinatalWomanView.Postcode=OX4+1SU

如何正确阅读邮政编码字符串参数,因为它显然不是空的?

HELP!

1 个答案:

答案 0 :(得分:0)

您可以拥有这样的视图模型:

public class AddressViewModel
{
    public string Postcode { get; set; }
}

然后通过使用Prefix属性修改参数来指定[Bind]

[HttpGet]
public ActionResult PostcodeCheck(
    [Bind(Prefix = "perinatalWomanView")]AddressViewModel model
)
{
    // use model.Postcode here ...
}

或者如果您不想使用Bind属性,请使用以下模型:

public class MyViewModel
{
    public AddressViewModel PerinatalWomanView { get; set; }
}

public class AddressViewModel
{
    public string Postcode { get; set; }
}

然后让你的控制器操作采用视图模型:

[HttpGet]
public ActionResult PostcodeCheck(MyViewModel model)
{
    // use model.PerinatalWomanView.Postcode here ...
}