Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save selected DropDownList value in ASP.NET MVC model for POST?

I have a property inside my model, like this:

 public IList<SelectListItem> AllCards { get; set; }

Property is being filled with SelectListItem's by controller with data from database.

Also, in my View is @Html.DropDownListFor(m=>m.AllCards,Model.AllCards,"--Select--"). Problem occures during POSTing of a view. That is, onSubmit my Model.AllCards is empty, although there is a value selected inside dropdownlist. I tried adding a new property to the model like this:

public SelectListItem SelectedCard

and then changing the view like this:

@Html.DropDownListFor(m=>m.AllCards,Model.SelectedCard,"--Select--")

but it gives me an error saying conversion not possible, sth like that.

What should I do to catch my dropdownlist value so that it can be inside model once POST version of a view is called? Thank you

P.S. I know there are ten similar questions but none of them help.

like image 262
Antun Tun Avatar asked Dec 21 '22 03:12

Antun Tun


1 Answers

This is how I would have done it.

Your view model could look like this and will have a list of cards:

public class CardViewModel
{
     public int CardId { get; set; }

     public IEnumerable<Card> Cards { get; set; }
}

I do not know what properties your card has but let me invent my own:

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

     public string Name { get; set; }
}

Your view will accept this view model:

@model YourProject.ViewModels.Cards.CardViewModel

Your HTML markup for the cards drop down list:

@Html.DropDownListFor(
     x => x.CardId,
     new SelectList(Model.Cards, "Id", "Name", Model.CardId),
     "-- Select --",
     new { id = "Cards" }
)
@Html.ValidationMessageFor(x => x.CardId)

Your action method when the view loads for the first time:

public ActionResult YourActionMethod()
{
     CardViewModel viewModel = new CardViewModel
     {
          Cards = cardService.FindAll()
     }

     return View(viewModel);
}

[HttpPost]
public ActionResult YourActionMethod(CardViewModel viewModel)
{
     if (!ModelState.IsValid)
     {
          return View(viewModel);
     }

     // Do what ever you need to do. The selected card's id will now be populated

     return RedirectToAction("List");
}

Regarding your JavaScript question I woudld advise that you start a new question, but I will give an outline on what you can look out for. Separate your JavaScript and HTML by adding the on change event using jQuery (use whatever you want to). For example:

<script>

     $(document).ready(function () {
          $("#Cards").change(function () {
               alert('cards value has changed');
          });
     });

</script>

I hope this helps.

like image 84
Brendan Vogt Avatar answered Jan 12 '23 00:01

Brendan Vogt