Reputation: 58
I have created a dropdownlist by fetching data from database.I want to display the selected value on click of submit. In controller I am trying to store the selected value in ViewBag
and display it. When I debugged the code, I came to know that viewbag stores null
value.The following line stores the value in viewbag.
ViewBag.scode = emp.Service_Code;
While debugging, Service_Code
shows the value but it gets stored as null
in ViewBag
. Please help me in solving this issue.
Model
public class Employee
{
public int Service_Code { get; set; }
public string Service_Name { get; set; }
public IEnumerable<SelectListItem> ser_code { get; set; }
}
View
@model mvclearn.Models.Employee
@{
ViewBag.Title = "menu";
}
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<div class="container">
@using (Html.BeginForm("save", "Test", FormMethod.Post))
{
@Html.DropDownListFor(m => m.Service_Code, Model.ser_code, "--select-",new { @class = "form-control" })
<input type="submit" value="submit" class="btn-block" />
}
</div>
<div>You entered:@ViewBag.scode</div>
Controller
public ActionResult menu()
{
RevenueDashboardEntities rdb = new RevenueDashboardEntities();
var model = new Employee()
{
ser_code = new SelectList(db.Services, "Service_Code", "Service_Name")
};
return View(model);
}
[HttpPost]
public ActionResult save(Employee emp)
{
RevenueDashboardEntities rdb = new RevenueDashboardEntities();
ViewBag.scode = emp.Service_Code;
return View("menu");
}
Upvotes: 0
Views: 48
Reputation: 62488
The selected value is already getting post in the action via model in Service_Code
property of it.
What you need here is return your model back to view and it will populate the selected value with what was selected at form post:
[HttpPost]
public ActionResult save(Employee emp)
{
RevenueDashboardEntities rdb = new RevenueDashboardEntities();
// this is needed to populate the items of dropdown list again
emp.ser_code = new SelectList(db.Services, "Service_Code", "Service_Name");
// sending model back to view
return View("menu",emp);
}
Now the value will be auto selected on page load after form is posted and you can display the value on the page inside div by writing:
<div>You entered: @Model.Service_Code</div>
Upvotes: 3