How to save dropdownlist selected value to the database int asp.net MVC 5

asp.net-mvc asp.net-mvc-4 entity-framework-6

Question

I am currently new to Asp.net MVC .In one of the view I add a dropdownlist and I bind this dropdownlist with my database like this

Controller CollegeController

[HttpGet]
public ActionResult Create()
{
    IEnumerable<SelectListItem> items = db.College_Names.Select(c => new SelectListItem { Value = c.id.ToString(), Text = c.Name });
    IEnumerable<SelectListItem> item = db.Stream_Names.Select(c => new SelectListItem { Value = c.id.ToString(), Text = c.Stream });
    ViewBag.CollName=items;
    ViewBag.StreamName = item;
    return View();
}

[HttpPost]
public ActionResult Create(College college)
{
    try
    {
        if(ModelState.IsValid)
        {
            db.Colleges.Add(college);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.CollName = db.Colleges;
        return View(college);
    }
    catch
    {
        return View();
    }
}

This is my model

public class College
{
    [Required]
    public int Id { get; set; }
    [Required]
    [Display(Name="College Name")]
    public int CollegeName { get; set; }
    [Required]
    public int Stream { get; set; }
    [Required]
    [Column(TypeName="varchar")]
    public string Name { get; set; }
    ....
    public virtual College_Name College_Name { get; set; }
    public virtual Stream_Name Stream_Name { get; set; }
}

This is My View

<div class="form-group">
    @Html.LabelFor(model => model.CollegeName, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("CollName", (IEnumerable<SelectListItem>)ViewBag.CollName, "Select College", new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.CollegeName, "", new { @class = "text-danger" })
    </div>
</div>
<div class="form-group">
    @Html.LabelFor(model => model.Stream, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("StreamName", (IEnumerable<SelectListItem>)ViewBag.StreamName, "Select Stream", new { @class = "form-control" })
       @Html.ValidationMessageFor(model => model.Stream, "", new { @class = "text-danger" })
    </div>
</div>

Now when I check my database after I save the CollegeName and Stream in the database is zero from the dropdownlist.

1
0
2/24/2016 6:15:08 AM

Accepted Answer

You have multiple problems with your code. Firstly you dropdownlists are binding to a properties named CollName and StreamName which do not even exist in your model.

Next you cannot name the property your binding to the same as the ViewBag property.

Your view code would need to be (and always use the strongly typed xxxFor() HtmHelper methods

@Html.DropDownListFor(m => m.CollegeName, (IEnumerable<SelectListItem>)ViewBag.CollName, "Select College", new { @class = "form-control" })
....
@Html.DropDownListFor(m => m.Stream, (IEnumerable<SelectListItem>)ViewBag.StreamName, "Select Stream", new { @class = "form-control" }

and in your POST method, the values of college.CollegeName and college.Stream will contain the ID's of the selected options.

You also need to repopulate the ViewBag properties when you return the view in the POST method (as you did in the GET method) or an exception will be thrown (and note that your current use of ViewBag.CollName = db.Colleges; will also throw an exception)

I also strongly suggest you start learning to use view models (views for editing should not use data models - refer What is ViewModel in MVC?) - and use naming conventions that reflect what your properties are, for example CollegeNameList, or CollegeNames, not CollName

1
5/23/2017 12:31:08 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow