使用父模型

时间:2015-11-19 16:52:51

标签: c# asp.net-mvc asp.net-mvc-4 razor

我已经在我的智慧结束时搜索了这个问题的答案。如果有人有任何建议,我们将不胜感激。

概述:

我添加了一个父模型,以便我可以在一个视图中引用多个模型。这样,@Html.ValidationMessageFor现在总是返回false,因为现在生成的URL显示为:

/Customer/isFieldValidJson?CUSTOMER.field=selectedValue

在我添加父模型之前,URL是(有效的):

/Customer/isFieldValidJson?field=selectedValue

以下是所有设置的方式:

父模型:

namespace WebProject
{
    public class CustomerClassOfTrade
    {
        public CUSTOMERS CUSTOMERS { get; set; }

        public CLASSOFTRADE CLASSOFTRADE { get; set; }
    }
}

CUSTOMERS模特:

namespace WebProject
{
    [MetadataType(typeof(CustomerMetaData))]
    public partial class CUSTOMERS
    {
    }

    public class CustomerMetaData
    {
        [Display(Name = "Field:")]
        [Required(ErrorMessage = "Required")]
        [StringLength(50, ErrorMessage = "Must be <= 50 characters")]
        [Remote("isFieldValidJson", "Customer", ErrorMessage = "Field not valid")]
        public string Field { get; set; }
    }
}

CLASSOFTRADE型号:

namespace WebProject
{
    [MetadataType(typeof(ClassOfTradeLevels))]
    public partial class CLASSOFTRADE
    {
    }

    public class ClassOfTradeLevels
    {
        [Display(Name = "Class of Trade L1:")]
        [StringLength(50, ErrorMessage = "Must be <= 50 characters")]
        public string ClassOfTradeL1 { get; set; }

        [Display(Name = "Class of Trade L2:")]
        [StringLength(50, ErrorMessage = "Must be <= 50 characters")]
        public string ClassOfTradeL2 { get; set; }
    }
}

客户控制人:

[CustomAuthorize(Roles = "Read/Write", PageType = "Customer")]
public ActionResult Create()
{
    var model = new CustomerClassOfTrade();
    var customer = new CUSTOMERS();
    var classoftrade = new CLASSOFTRADE();

    ViewBag.FieldArray = db.FIELDS.ToList();

    model.CUSTOMERS = customer;
    model.CLASSOFTRADE = classoftrade;

    return View(model);
}

public JsonResult isFieldValidJson(string field)
{
    return Json(isFieldValid(field), JsonRequestBehavior.AllowGet);
}

public bool isFieldValid(string field)
{
    return db.FIELDS.Any(ss => ss.Field == field);
}

创建视图:

@model WebProject.CustomerClassOfTrade

@{
    ViewBag.Title = "Create Customer";
}

<h2>@ViewBag.Title</h2>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Customer</legend>

        <div class="editor-label">
            @Html.LabelFor(m => m.CUSTOMERS.Field) 
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(m => m.CUSTOMERS.Field, new SelectList(ViewBag.FieldArray, "Field", "Field"), "Select")
            @Html.ValidationMessageFor(m => m.CUSTOMERS.Field)
        </div>
    </fieldset>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

如果需要更多信息,请与我们联系。谢谢!

1 个答案:

答案 0 :(得分:1)

将远程验证操作更改为:

public JsonResult isFieldValidJson([Bind(Prefix = "CUSTOMERS")] string field)
{
    return Json(isFieldValid(field), JsonRequestBehavior.AllowGet);
}