Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i create a SelectListItem() with Int Value

I have the folloiwng 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 the ToString() from the ORG_ID , i will get an error that "can not explicitly convert long to string". so it seems that i have to define both the value and the text for the SelectListItem as strings. but since the SelectListItem should hold long , so is there a way to pass the values of the SelectListItem as long instead of strings?

like image 301
john Gu Avatar asked Jul 28 '14 16:07

john Gu


People also ask

What is SelectListItem MVC?

SelectListItem is a class which represents the selected item in an instance of the System. Web. Mvc.


1 Answers

...so is there a way to pass the values of the SelectListItem as long instead of strings?

No. And it doesn't make any sense to do so as when it is rendered, it's just HTML which has no concept of long.

If we have the 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 "Test.cshtml":

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

The generated HTML is

<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 post to this action, text of your number is effectively parsed back into your desired type by the Model Binder

[HttpPost]
public ActionResult Test(int? id)
{
    var selectedValue = id.HasValue ? id.ToString() : "All";

    return Content(String.Format("You selected '{0}'", selectedValue));
}

And the above works as you might expect.

like image 79
dav_i Avatar answered Oct 02 '22 18:10

dav_i