touinta
touinta

Reputation: 1031

store a value from dropdown list to database MVC 5

Hello in my app I have a dropdown list

in my controller I use this

public ActionResult Create()
    {

        webdata db = new webdata();
        ViewBag.annCategories = new SelectList(db.annCategories, "kind", "an_kindtext");
        return View();

    }

EDIT in my HttpPost I have

    [HttpPost]
    [ValidateAntiForgeryToken]

    public ActionResult Create([Bind(Include = "ann_ID,Pubdate,kind,title")] announcements announcements)
    {
        if (ModelState.IsValid)
        {
            db.announcements.Add(announcements);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(announcements);
    }

and in my view I have this

@Html.DropDownList("annCategories",null, new { id = "annCategories" })

I see the values in my dropdown list, when I click the create button a new record is stored in the database. But it always saves the "Select a category" which is the first option. Can someone help with this? thank you

EDIT

My announcement model

public class announcements
{
    [Key]
    [Display(Name = "ID")]
    public int ann_ID { get; set; }


    [Display(Name = "Date")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
    public DateTime Pubdate { get; set; }

    [Display(Name = "Category")]
    public int kind { get; set; }


    [Display(Name = "title")]
    public String title { get; set; }

    }

My announcement categories model

public class annCategories
{

    [Key]
    [Display(Name = "Category")]
    public int kind { get; set; }


    [Display(Name = "Description")]
    public String an_kindtext { get; set; }

}

Upvotes: 0

Views: 2900

Answers (1)

user3559349
user3559349

Reputation:

It is not saving "Select a category". It is saving the default values of you model because you never bind anything to property kind so when you submit the form the value of kind is 0.

Start by creating a view model to represent what you want to display in the view

public class AnouncementVM
{
    public int? ID{ get; set; }
    [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}"] // see notes below
    public DateTime Date { get; set; }
    public int Category { get; set; }
    public string Title{ get; set; }
    public IEnumerable<SelectListItem> CategoryList { get; set; }
}

Note the [DataType(DataType.Date)] adds the type="date" attribute in order to render the browsers datepicker (which is only implemented in Chrome and Edge) so unless your using that, then it can be removed, but if you are using it, then you must also use [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] (i.e. the format must be yyyy-MM-dd)

Then in the GET method

public ActionResult Create()
{
    var model = new AnouncementVM
    {
        CategoryList = new SelectList(db.annCategories, "kind", "an_kindtext")
    };
    return View(model)
}

and in the view

@Html.DropDownListFor(m => m.Category, Model.CategoryList, "Please select")

and in the POST method

[HttpPost]
public ActionResult Create(AnouncementVM model)
{
    if (!ModelState.IsValid)
    {
        model.CategoryList = new SelectList(db.annCategories, "kind", "an_kindtext");
        return View(model);
    }
    announcements data = new announcements
    {
        Pubdate = model.Date,
        kind = model.Category,
        title = model.Title
    };
    db.announcements.Add(data);
    db.SaveChanges();
    return RedirectToAction("Index");
}

Upvotes: 1

Related Questions