Giorgi Asanidze
Giorgi Asanidze

Reputation: 36

Pass dropdownlist value to controller

I have dropdownlist and want to pass value in Controller. View

@using (Html.BeginForm())
{  
    @Html.DropDownList("dropOrg", ViewBag.dropOrg as SelectList)
    <input type="submit" value="save" />
}

Controller

foreach (int tmp in org)
{
   string s = tmp + " - " + orgNames[tmp];
   SelectListItem item1 = new SelectListItem() { Text = s, Value = tmp.ToString() };
   items.Add(item1);
}
ViewBag.dropOrg = items;

What should i do?

Upvotes: 1

Views: 169

Answers (1)

SᴇM
SᴇM

Reputation: 7213

It will be better if you create ViewModel for your View:

public class SampleViewModel
{
    public string DropDownListValue { get; set; }
}

then in your controller's get method:

public ActionResult SomeAction()
{
    var org = GetOrg(); //your org
    var orgNames = GetOrgNames(); //your orgNames

    // . . .

    ViewBag.DropDownListValue = new SelectList(org.Select(s => 
    new SampleViewModel 
    {  
        DropDownListValue = $"{s} - {orgNames[s]}"
    }, "DropDownListValue", "DropDownListValue");
    return View(new SampleViewModel())
}

your SomeAction View:

@model YourAppNamespace.SampleViewModel
<h1>Hello Stranger</h1>

@using (Html.BeginForm())
{
    @Html.DropDownList("DropDownListValue")
    <input type="submit" value="Submit"/>
}

Note that:

The DropDownList helper used to create an HTML select list requires a IEnumerable<SelectListItem>, either explicitly or implicitly. That is, you can pass the IEnumerable<SelectListItem> explicitly to the DropDownList helper or you can add the IEnumerable<SelectListItem> to the ViewBag using the same name for the SelectListItem as the model property.

We have used here implicit passing, that is we have used same name for SelectListItem and ViewBag (which is DropDownListValue).

Then when you hit Submit, you need HttpPost method for SomeAction:

[HttpPost]
public ActionResult SomeAction(SampleViewModel model)
{
    var org = GetOrg(); //your org
    var orgNames = GetOrgNames(); //your orgNames

    //. . . Validation etc..

    ViewBag.DropDownListValue = new SelectList(org.Select(s => 
    new SampleViewModel 
    {  
        DropDownListValue = $"{s} - {orgNames[s]}"
    }, "DropDownListValue", "DropDownListValue", model.DropDownListValue);


    var doSomething = model.DropDownListValue; //Your selected value from DropDownList
    return View(model)
}

References: DotNetFiddle Example, Using the DropDownList Helper with ASP.NET MVC

Upvotes: 1

Related Questions