I'm new to asp mvc, so I was trying to understand how to get selected value from drop down list. Now what I want is to see the selected value as text in my view. After searching several examples, I have this code in controller:
public ActionResult Index()
{
TaskModel task = new TaskModel();
task.Tasks = FillTaskList();
return View(task);
}
[HttpPost]
public ActionResult Index(TaskModel task)
{
task.Tasks = FillTaskList();
ViewBag.Message = task.TaskName;
return View(task);
}
private static List<SelectListItem> FillTaskList()
{
List<SelectListItem> items = new List<SelectListItem>();
string constr = ConfigurationManager.ConnectionStrings["contingentConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = " SELECT TaskId, TaskName FROM Task";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
items.Add(new SelectListItem
{
Text = sdr["TaskName"].ToString(),
Value = sdr["TaskId"].ToString()
});
}
}
con.Close();
}
}
return items;
}
This is my view:
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
@model WebApplication1.Models.TaskModel
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
</head>
<body>
<div>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<div class="form-group">
@Html.DropDownListFor(m => m.TaskId, Model.Tasks, "--Select task--", null)
</div>
<button type="Submit" class="btn btn-success submit">Send</button><br/>
<span style="color:green">@Html.Raw(ViewBag.Message)</span>
}
</div>
</body>
</html>
And this is my model:
namespace WebApplication1.Models
{
public class TaskModel
{
public List<SelectListItem> Tasks { get; set; }
public int TaskId { get; set; }
public string TaskName { get; set; }
}
}
The problem is that I keep getting null instead of "TaskName" value here,
ViewBag.Message = task.TaskName;
but
ViewBag.Message = task.TaskId;
is processing correctly and I can see it in ViewBag.Message. What am I doing wrong?
TaskId(from the dropdown) is the only property in the payload or at least the only property that has a value in the payload. The ASP.NET model binding does it best to map POSTed value into the type you specify -- but it does not have any past state. If you think about your use case,TaskIdis the only value that is needed to be posted back. You should use the ID that gets posted back to query the latest values (includingTaskName) for that TaskId.