Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - Get Id from a dropdownlist

I'm new in ASP.NET MVC and i have a problem. I needed to get a string "Category" from a dropdownlist, that was my code:

var CList = new List<string>();

StreetFooder sf = db.StreetFooders.Single(s => s.User.UserName == this.User.Identity.Name);

var Cqry = from d in db.Categories
where !d.IsDeleted && d.StreetFooder.Id == sf.Id
orderby d.Name
select d.Name;

CList.AddRange(Cqry.Distinct());
ViewBag.CategoryList = new SelectList(CList);

And the view:

<div class="col-md-10">

@Html.DropDownListFor(model => model.Category, (SelectList)ViewBag.CategoryList, new { @class = "form-control" })

@Html.ValidationMessageFor(model => model.Category, "", new { @class = "text-danger" })
</div>

And that worked for me. After that, i realized i made a mistake and changed my string Category attribute in:

public virtual Categories Type { get; set; }

Now i want to save on my db the ID instead of string, but still want to see my string when select from dropdown list...but don't know how.

like image 241
ThePrati Avatar asked Dec 03 '25 21:12

ThePrati


1 Answers

Use SelectListItem to create the SelectList, there you can specify Value = your id and Text = display text

https://msdn.microsoft.com/en-us/library/system.web.mvc.selectlistitem(v=vs.118).aspx

var CList = new List<SelectListItem>();

StreetFooder sf = db.StreetFooders.Single(s => s.User.UserName == this.User.Identity.Name);

var Cqry = from d in db.Categories
where !d.IsDeleted && d.StreetFooder.Id == sf.Id
orderby d.Name
select d;

CList.AddRange(Cqry.Distinct().Select(x => new SelectListItem 
{
    Value = x.Id.ToString(),
    Text = d.Name
}));
ViewBag.CategoryList = new SelectList(CList);

You can even omit using the SelectList and simply pass a List<SelectListItem> if I recall correctly.

like image 158
Santhos Avatar answered Dec 05 '25 12:12

Santhos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!