MVC3远程验证IEnumerable中的字段

时间:2012-02-29 18:06:58

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

我的模型类的IEnumerable内有一个对象,呈现的HTML看起来像

<input data-val="true" data-val-number="The field money must be a number." data-val-remote="&amp;#39;money&amp;#39; is invalid." data-val-remote-additionalfields="*.money" data-val-remote-url="/RemoteValidator/ValidateMoney" data-val-required="The money field is required." id="BudgetDetails_0__BudgetData_Money" name="BudgetDetails[0].BudgetData.Money" type="text" value="100" />
<span class="field-validation-valid" data-valmsg-for="BudgetDetails[0].BudgetData.Money" data-valmsg-replace="true"></span>

模型类看起来像

public class MyViewModel
{
    public IEnumerable<Budget> BudgetDetails { get; set; }
}

public class Budget
{
    public int SomeIdentifier { get; set; }
    public BudgetValues BudgetData { get; set; }
}

public class BudgetValues
{
    [Remote("ValidateMoney", "RemoteValidator")]
    public decimal? Money { get; set; }

    // other properties
}

查看

@model DictionaryAndRemote.Models.MyViewModel
<!DOCTYPE html>
<html>
<head>
    <title>Index</title>
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
</head>
<body>
    @using (Html.BeginForm())
    {
        @Html.EditorFor(x => x.BudgetDetails)
        <br />
        <input type="submit" value="Submit user Data" />
    }
</body>
</html>

编辑模板Views\Shared\EditorTemplates\Budget.cshtml

@model DictionaryAndRemote.Models.Budget
<div id="@Model.SomeIdentifier.ToString()">
    <div>
        @Html.TextBoxFor(x => x.BudgetData.Money)
        @Html.ValidationMessageFor(x => x.BudgetData.Money)
    </div>
</div>

UI将触发Ajax调用http://localhost:4276/RemoteValidator/ValidateMoney?BudgetDetails%5B0%5D.BudgetData.Money=500,但遗憾的是路由表无法将请求与我的操作方法匹配

    public ActionResult ValidateMoney(decimal money)
    {
        return Json("I will always fail you.", JsonRequestBehavior.AllowGet);
    }

因为参数名称不匹配。由于is位于IEnumerable中,因此参数名称甚至是动态BudgetDetails[0].BudgetData.MoneyBudgetDetails[1].BudgetData.Money等等。

当然,我总是可以调整行动方式

    public ActionResult ValidateMoney()
    {
        string parameter = Request.QueryString.ToString();
        return Json("I will always fail you.", JsonRequestBehavior.AllowGet);
    }

并使用非常原始的方式来解析查询字符串,但我不认为这是最优雅的解决方案。

有人有分享的经验吗?

1 个答案:

答案 0 :(得分:0)

试试这种方式。

public JsonResult ValidateMoney([Bind(Include = "Money")]BudgetValues budgetValues)
{
 if(null != budgetValues)
 {
  decimal money = budgetValues.Money 
 }
 return Json("I will always fail you.", JsonRequestBehavior.AllowGet); 
}