Sajid8212
Sajid8212

Reputation: 19

Value from DropDownListFor is not saving value to Database

Here is my view

<div class="form-group">
    @Html.LabelFor(model => model.SubCatagory, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(model => model.SubCatagory, new SelectList(ViewBag.SubCategories, "Id", "Name", "Category"))
        @Html.ValidationMessageFor(model => model.SubCatagory, "", new { @class = "text-danger" })
    </div>
</div>

And here is the method where I'm saving data.

 dbContext.Products.Add(product);
 dbContext.SaveChanges();

It is saving all the values to database except SubCatagoryId.. Can anyone please help me ?

Upvotes: 0

Views: 148

Answers (1)

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

The SubCatagory property contains null value because it's a complex object property bound for SubCatagory class, which DropDownListFor returns single selected value instead of entire class properties. You should do one of these:

Option A: Create selected value property

Create an int property which will hold selected value from DropDownListFor on Product class, and then you can assign SubCatagory property inside controller by querying from database based from passed value in newly created property.

Model

public class Product 
{ 
    [Key] 
    public int Id { get; set; }

    [Display(Name = "Sub Catagory")] 
    public int SelectedSubCatagory { get; set; }

    // other properties
}

View

<div class="form-group">
    @Html.LabelFor(model => model.SelectedSubCatagory, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(model => model.SelectedSubCatagory, new SelectList(ViewBag.SubCategories, "Id", "Name", "Category"))
        @Html.ValidationMessageFor(model => model.SelectedSubCatagory, "", new { @class = "text-danger" })
    </div>
</div>

Option B: Use existing child property of SubCatagory class

Suppose you have ID property declared inside SubCatagory class like this:

public class SubCatagory
{
    public int Id { get; set; }

    public string Name { get; set; }

    // other properties
}

You may use it to bind on DropDownListFor helper as in example below:

View

<div class="form-group">
    @Html.LabelFor(model => model.SubCatagory.Id, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(model => model.SubCatagory.Id, new SelectList(ViewBag.SubCategories, "Id", "Name", "Category"))
        @Html.ValidationMessageFor(model => model.SubCatagory.Id, "", new { @class = "text-danger" })
    </div>
</div>

Note that if you take this option, make sure that SubCatagory property is already instantiated (with new keyword) in Product class to avoid NullReferenceException when using its child properties.

Reference:

How to simple Html.DropDownListFor MVC.NET (Nested Viewmodels)

Upvotes: 1

Related Questions