Reputation: 817
So i get values for my drop down list but i wanted to get selected value from this dropdown. How to do this ?
Model:
public partial class Region
{
public int Id_regionu { get; set; }
public string Nazwa { get; set; }
}
Controller:
public class HomeController : Controller
{
private inzS9776Entities db = new inzS9776Entities();
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
public ActionResult Index()
{
ViewBag.Regiony = new SelectList(db.Region,"Id_regionu", "Nazwa");
return View();
}
and View with dropdown:
<div class="jumbotron">
<legend>
<h2>Wyszukaj wycieczkę</h2></legend><br/>
<form action="">
<div class="container">
Wybierz kierunek:
@Html.DropDownList("Regiony",null, String.Empty)<br />
Data wyjazdu:
<input class="date" type="date" name="startDate"><br><br>
</div>
</form>
`
Upvotes: 0
Views: 155
Reputation: 8286
Replace your <form action="">
to:
@using (Html.BeginForm("MyActionName") {
// ...
//here add to your dropdown and give it a name
@Html.DropDownList("Regiony", null, String.Empty)
// ...
}
The name attribute of your <select>
element (dropdown list) will be "Regiony".
In your controller:
public ActionResult MyActionName(string Regiony) {
// here Regiony variable contains the selected value.
// ...
}
Upvotes: 1
Reputation: 1666
Here is an approach which I take;
1) Retreive the items and store it in a list of SelectListItem. 2) Use the list of SelectListItem to assign it to a drop down list. 3) Use the model field to bind the drop down list with the selected value
View
<div class="col-sm-8">
@{
List<SelectListItem> listItems = new List<SelectListItem>();
foreach (LookupData l in Model.HeatingTypeData)
{
listItems.Add(new SelectListItem { Text = l.LookupDescription, Value = l.LookupCode });
}
}
@Html.DropDownListFor(m => m.HeatingType, listItems, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.HeatingType)
</div>
Models: The model (VoidProperty) used in the example contains the HeatingType as a List of LookupData and a method to get the list:
public List<LookupData> HeatingTypeData { get; set; }
public static List<LookupData> GetHeatingType()
{
return LookupData.GetDataList("HeatingType").OrderBy(m => m.SortOrder).ToList();
}
and then the LookupData:
public class LookupData : ILookup
{
public string LookupCode { get; set; }
public string LookupDescription { get; set; }
public int SortOrder { get; set; }
public static List<LookupData> GetDataList(string LookupGroup)
{
DBContexts.VoidsDBContext context = new DBContexts.VoidsDBContext();
var Params = new SqlParameter { ParameterName = "LookupGroup", Value = LookupGroup };
return context.Database.SqlQuery<LookupData>("p_LookupList @LookupGroup", Params).ToList();
}
}
The controller returns the view and pass an instance of the model;
VoidProperty _property = new VoidProperty();
......
......
_property.HeatingTypeData = VoidProperty.GetHeatingType();
......
return View(_property);
Upvotes: 0