2

我正在为一个项目使用 MVC 4 和实体框架。我有一个使用ProductViewModel强类型的Create Product View

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] 是问题的关键......

调试截图

有什么想法可以让这个字段成为可选的,然后只需在我的下拉列表中选择一个产品类型来创建一个新产品吗?

4

1 回答 1

0

我想,你有3个选择:

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

2) 将一些属性添加到您的视图模型(例如 bool)并编写自定义验证属性(例如 IfPropertyAThenValidate)或类似的东西

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

ModelState modelStateOfModel = ModelState["Model"];

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

if (ModelState.IsValid)
{
   ...
}
于 2013-04-29T14:03:25.940 回答