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'm just getting started with Asp.net MVC. I add a dropdown list to one of the views and link it to my database in the following way.

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 example.

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 How I Feel

<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>

When I examine my database now, following the saving ofCollegeName and Stream From the dropdown list, zero is in the database.

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

Accepted Answer

ZZZ_tmp
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