MVC 4 - 实体框架,ViewModel和验证

时间:2013-04-29 13:15:00

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

我正在为项目使用MVC 4和Entity Framework。我有创建产品视图,其强类型为 ProductViewModel

public class ProductViewModel
{
    public Product Product { get; set; }
    public ProductType ProductType { get; set; }

    public List<SelectListItem> ProductTypes { get; set; }
    public List<SelectListItem> ProductCompanies { get; set; }

    [RegularExpression(@"^[a-zA-Z0-9àéèêçñ\s][a-zA-Z0-9àéèêçñ\s-]+$", ErrorMessage = "Invalid name !")]
    public string Model { get; set; }

    [RegularExpression(@"^[a-zA-Z0-9àéèêçñ\s][a-zA-Z0-9àéèêçñ\s-]+$", ErrorMessage = "Invalid name !")]        
    public string CompanyName { get; set; }
}

在我看来,我有字段和下拉列表,它重新组合了一些产品类型(产品由产品类型组成)。问题是,当下拉列表中没有所需的产品类型时,我允许用户创建一个新的产品类型,如下所示:

@model BuSIMaterial.Models.ProductViewModel
@{
    ViewBag.Title = "Create a material";
}

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

    <fieldset>
        <legend>Create a material</legend>
        <div class="editor-label">
            Product type : <a class="product_type" id="product_type_link">Using a new model</a>
        </div>
        <div id= "existing_product_type" class="editor-field">
            @Html.DropDownListFor(p => p.Product.Id_ProductType, Model.ProductTypes)
            @Html.ValidationMessageFor(model => model.Product.Id_ProductType)
        </div>
        <div id="new_product_type">
        <div class="editor-label">
            Model : 
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.Model, new { maxlength = 50, id = "model" })
            @Html.ValidationMessageFor(model => model.Model)
        </div>

        <div class="editor-label">
            Company : <a class="company" id="company_link">Using a new company name</a>
        </div>
        <div id="existing_company" class="editor-field">
            @Html.DropDownListFor(p => p.ProductType.Id_ProductCompany, Model.ProductCompanies)
            @Html.ValidationMessageFor(model => model.ProductType.Id_ProductCompany)
        </div>
        <div id="new_company">
             <div class="editor-label">
                Name : 
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(model => model.CompanyName, new { id = "company_name"})
                @Html.ValidationMessageFor(model => model.CompanyName)
            </div>       
        </div>
        </div>
        <div class="editor-label">
            Price :
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.Product.CatalogPrice)
            @Html.ValidationMessageFor(model => model.Product.CatalogPrice)
        </div>
        <div class="editor-label">
            Purchase date :
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.Product.PurchaseDate, new { @class = "datepicker"})
            @Html.ValidationMessageFor(model => model.Product.PurchaseDate)
        </div>
        <div class="editor-label">
            Serial number :
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.Product.SerialNumber, new { maxlength = 50 })
            @Html.ValidationMessageFor(model => model.Product.SerialNumber)
        </div>
        <div class="form-actions">
          <button type="submit" class="btn btn-primary">Create</button>
        </div>
    </fieldset>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/jqueryui")
    @Styles.Render("~/Content/themes/base/css")

    <script type="text/javascript">

        $(document).ready(function () {

            $("#product_type_link").click(function () {

                if ($("#new_product_type").css("display") == "block") {

                    $("#new_product_type").css("display", "none");
                    $("#existing_product_type").css("display", "block");
                    $("#product_type_link").text("Using a new model");
                    $("#model").val("");
                    $("#company_name").val("");

                }
                else {
                    $("#new_product_type").css("display", "block");
                    $("#existing_product_type").css("display", "none");
                    $("#product_type_link").text("Using an existing model")
                }
            });

            $("#company_link").click(function () {

                if ($("#new_company").css("display") == "block") {

                    $("#new_company").css("display", "none");
                    $("#existing_company").css("display", "block");
                    $("#company_link").text("Using a new company name");
                    $("#company_name").val("");

                }
                else {
                    $("#new_company").css("display", "block");
                    $("#existing_company").css("display", "none");
                    $("#company_link").text("Using an existing company name")
                }
            });

        });

    </script>

}

通过这样做,在我的操作中,ModelState存在一个无效的问题。我做了几个测试,我认为模型字段(所以当用户想要创建新的产品类型时)是问题:似乎这个字段是必需的(应该是可选的)。这是我的行动:

[HttpPost]
public ActionResult Create(ProductViewModel pvm)
{
    var productTypeList = from obj in db.ProductTypes orderby obj.ProductCompany.Name ascending where !((from element in db.VehicleTypes select element.Id_ProductType).Contains(obj.Id_ProductType)) select obj;

    ViewBag.Id_ProductType = new SelectList(productTypeList, "Id_ProductType", "Information", pvm.Product.Id_ProductType);
    pvm.ProductTypes = productTypeList.ToList().Select(p => new SelectListItem { Text = p.Information, Value = p.Id_ProductType.ToString() }).ToList();

    ViewBag.Id_ProductCompany = new SelectList(db.ProductCompanies, "Id_ProductCompany", "Name", pvm.ProductType.Id_ProductCompany);
    pvm.ProductCompanies = db.ProductCompanies.ToList().Select(pc => new SelectListItem { Text = pc.Name, Value = pc.Id_ProductCompany.ToString() }).ToList();


    Product product = null;
    ProductType productType = null;

    if (ModelState.IsValid)
    {

        ModelStateDictionary errors = Validator.isValid(pvm.Product);

        if (errors.Count > 0)
        {
            ModelState.Merge(errors);
            return View(pvm);
        }

        if (!string.IsNullOrEmpty(pvm.Model))
        {
            if (!string.IsNullOrEmpty(pvm.CompanyName))
            {
                ProductCompany productCompany = new ProductCompany()
                {
                    Name = pvm.CompanyName
                };

                productType = new ProductType()
                {
                    Model = pvm.Model,
                    ProductCompany = productCompany
                };

                product = new Product()
                {
                    PurchaseDate = pvm.Product.PurchaseDate,
                    SerialNumber = pvm.Product.SerialNumber,
                    CatalogPrice = pvm.Product.CatalogPrice,
                    ProductType = productType
                };
            }
            else
            {
                productType = new ProductType()
                {
                    Model = pvm.Model,
                    Id_ProductCompany = pvm.ProductType.Id_ProductCompany
                };

                product = new Product()
                {
                    PurchaseDate = pvm.Product.PurchaseDate,
                    SerialNumber = pvm.Product.SerialNumber,
                    CatalogPrice = pvm.Product.CatalogPrice,
                    ProductType = productType
                };
            }
        }
        else
        {
            productType = new ProductType()
            {
                Id_ProductType = pvm.ProductType.Id_ProductType,
                Id_ProductCompany = pvm.ProductType.Id_ProductCompany                    
            };

            product = new Product()
            {
                PurchaseDate = pvm.Product.PurchaseDate,
                SerialNumber = pvm.Product.SerialNumber,
                CatalogPrice = pvm.Product.CatalogPrice,
                ProductType = productType
            };
        }

        db.Products.AddObject(product);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(pvm);
}

编辑:这是调试器的截图。当我检查值时,键[5]是问题的关键......

Debug screenshot

是否有任何想法让这个字段成为可选项,然后只需在我的下拉列表中选择产品类型来创建新产品?

1 个答案:

答案 0 :(得分:0)

我认为,您有3种选择:

1)重写你的正则表达式以支持空值

2)向viewmodel添加一些属性(例如bool)并编写自定义验证属性(例如IfPropertyAThenValidate)或类似的东西

3)如果您的ViewModel包含现有产品类型,请忽略Model属性: e.g:

ModelState modelStateOfModel = ModelState["Model"];

if (modelStateOfModel != null)
{
    modelStateOfModel.Errors.Clear();
}

if (ModelState.IsValid)
{
   ...
}