Question

I have a table Product, a table ProductType and finally a table ProductCompanies. Here is their relation :

Products tables relation

I have a ProductViewModel which is like this :

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

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

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

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

I have a personalized Create View which work like this : there is a dropdown list which contains all the existing product types. If the user wants to create a new one, it is possible by clicking on a link which makes a hidden section appear. In this section, you can add a new model name and precise the company :

@model BuSIMaterial.Models.ProductViewModel

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@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.ProductType.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.ModelName, new { maxlength = 50, id = "model"})
                @Html.ValidationMessageFor(model => model.ModelName)
            </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.Product.ProductType.Id_ProductCompany, Model.ProductCompanies)
                @Html.ValidationMessageFor(model => model.Product.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">
            Catalog price : 
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.Product.CatalogPrice)
            @Html.ValidationMessageFor(model => model.Product.CatalogPrice)
        </div>
        <div class="editor-label">
            Serial number : 
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.Product.SerialNumber)
            @Html.ValidationMessageFor(model => model.Product.SerialNumber)
        </div>
        <div class="editor-label">
            Purchase date : 
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.Product.PurchaseDate, new { id = "datepicker"})
            @Html.ValidationMessageFor(model => model.Product.PurchaseDate)
        </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>
}

In my post action, I just check if the user has entered something in the hidden field. If it is done, I do some work but nothing really complicated :

[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.Product.ProductType.Id_ProductCompany);
    pvm.ProductCompanies = db.ProductCompanies.ToList().Select(c => new SelectListItem { Text = c.Name, Value = c.Id_ProductCompany.ToString() }).ToList();

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

    ProductType productType = null; 

    if (ModelState.IsValid)
    {
        ModelStateDictionary errors = Validator.isValid(pvm.Product);

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

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

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

            }
            else
            {
                productType = new ProductType()
                {
                    Model = pvm.ModelName,
                    Id_ProductCompany = pvm.Product.ProductType.Id_ProductCompany
                };
            }
        }
        else
        {
            productType = new ProductType()
            {
                Id_ProductType = pvm.Product.Id_ProductType,
                Id_ProductCompany = pvm.Product.ProductType.Id_ProductCompany
            };
        }

        product.ProductType = productType;
        db.Products.AddObject(product);
        db.SaveChanges();

        return RedirectToAction("Index");
    }

    return View(pvm);
}

My problem is that I never reach the code inside the if(ModelState.isValid) because my ModelState is not valid... And I don't know why ! Having debug several times, I found that the Product.ProducType.Model of my ViewModel is null (and shouldn't because if the user selects something in the dropdown list it's okay and if he enters a new model name it should be okay).

Any idea about what's going on?

EDIT : The HttpGet of the Create Action :

public ActionResult Create()
{
    ProductViewModel pvm = new ProductViewModel();
    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.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.ProductCompanies = db.ProductCompanies.ToList().Select(c => new SelectListItem { Text = c.Name, Value = c.Id_ProductCompany.ToString() }).ToList();


    return View(pvm);
}
Was it helpful?

Solution

As from the comments: Change @Html.DropDownListFor(p => p.Product.ProductType.Id_ProductType, Model.ProductTypes) in your view to @Html.DropDownListFor(p => p.Product.Id_ProductType, Model.ProductTypes) i.e. just setting the ID_ProductType of the Product to the selected value, and not creating a (new) ProductType object with that id.

Then, in the Create method, change

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

    product.ProductType = productType;
    db.Products.AddObject(product);
    db.SaveChanges();

to

    else
    {
        product.Id_ProductType = pvm.Product.Id_ProductType,
    }

    product.ProductType = productType;
    db.Products.AddObject(product);
    db.SaveChanges();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top