简体   繁体   中英

How to pass value of selected dropdownlist from view to the controller

I have a dropdown in my view, couple of other controls and a input button to save the data. On saving I have ActionReult Save () which needs the value I selected in the dropdownlist. How can I get the selected value of the dropdownlist on my controller Actionresult Save()

View:
------
Collapse | Copy Code
var docTypes = Model.DocumentTypes.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString()}).AsEnumerable();
@Html.DropDownList("SelectedDocumentType", docTypes, "--select--", new { @class = "ddSelect" })

Model:
-----
Collapse | Copy Code
public IEnumerable DocumentTypes { get; set; }

   Controller:
   -----------
   Collapse | Copy Code
   [HttpParamAction]
   [HttpPost]
   [ValidateInput(false)]
       public ActionResult Save()
 {
   int DocumentType = // I have to assign the selected value of the dropdownlist here
    }

Add a property to your model to store the value. I'm assuming that id is an int and there's no need for you to use ToString() as you currently do. So in your model add:

public int DocumentTypeId {get;set;}

Then you should use the HtmlHelper method that binds the drop down to the value, DropDownListFor. This gives you:

@Html.DropDownListFor(model => model.DocumentTypeId, new SelectList(Model.DocumentTypes, "Id", "Name"), "--select--", new { @class = "ddSelect" })

and you can remove the docTypes variable creation and initialisation.

EDIT: Another issue I've noticed is that your controller method Save() doesn't have any parameters. To be able to read POSTed data you'll need to have your model as a parameter. So if it was called MyModel your controller method's signature would be:

public ActionResult Save(MyModel model)

and then to assign the value to the variable you want it in would simply be:

int DocumentType = model.DocumentTypeId;

Try using int.Parse(drop.SelectedValue) or int.Parse(drop.SelectedValue.Trim()) instead of Int32.Parse(drop.SelectedValue.ToString()) . drop.SelectedValue is already in string format so you need not convert it using ToString

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM