How can I create SelectListItem () with Int Value

I have the following code inside my asp.net mvc action method: -

var CustomerData = customerlist.Select(m => new SelectListItem() { Text = m.SDOrganization.NAME, Value = m.SDOrganization.ORG_ID.ToString(), }); 

Currently, if I remove ToString () from ORG_ID, I will get an error that "cannot explicitly convert long to string". so it seems to me that I should define both the value and the text for SelectListItem as a string. but since the SelectListItem element must last a long time, is there a way to pass the SelectListItem values ​​for how long, rather than strings?

+6
source share
1 answer

... so is there a way to pass SelectListItem values ​​as long as strings?

No. And it makes no sense to do this, since when rendering it is just HTML, which has no concept of long .

If we have an action

 public ActionResult Test() { var dictionary = new Dictionary<int, string> { { 1, "One" }, { 2, "Two" }, { 3, "Three" } }; ViewBag.SelectList = new SelectList(dictionary, "Key", "Value"); return this.View(); } 

and the following view of "Test.cshtml":

 @using (Html.BeginForm()) { @Html.DropDownList("id", ((SelectList)ViewBag.SelectList), "All") <input type="submit" value="Go" /> } 

HTML generated

 <form action="/home/test" method="post"> <select id="id" name="id"> <option value="">All</option> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </select> <input type="submit" value="Go"> </form> 

and when we send this action, the text of your number is effectively parsed back to the desired type using model binding

 [HttpPost] public ActionResult Test(int? id) { var selectedValue = id.HasValue ? id.ToString() : "All"; return Content(String.Format("You selected '{0}'", selectedValue)); } 

And it works as you would expect.

+14
source

Source: https://habr.com/ru/post/972972/


All Articles