1

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?

3
  • Use your browser console or Fiddler or similar to look at the payload that is getting posted. I expect that you will find that 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, TaskId is the only value that is needed to be posted back. You should use the ID that gets posted back to query the latest values (including TaskName) for that TaskId. Commented Feb 22, 2019 at 21:04
  • 1
    Seems this is really so, thanks for advice! Commented Feb 23, 2019 at 15:57
  • My pleasure. Welcome to StackOverflow -- #SOReadyToHelp Commented Feb 24, 2019 at 17:52

2 Answers 2

0

Your problem: In your action POST, it only mapping TaskId from dropdown, you need filter in TaskList to check selected task in list. If selected task in list, then set ViewBag.Message = selectedTask.Text

You need update your action code for POST:

[HttpPost]
 public ActionResult Index(TaskModel task)
 {
            task.Tasks = FillTaskList();
            var selectedTask = task.Tasks.FirstOrDefault(c => c.Value == task.TaskId.ToString());
            if (selectedTask != null)
            {
                ViewBag.Message = selectedTask.Text;
            }

            return View(task);
 }
Sign up to request clarification or add additional context in comments.

Comments

0

Use Html.HiddenFor Helper method to create a hidden variable in the form for this property

@Html.HiddenFor(x => x.TaskName)

Use javascript to set selected text

$(function () {
  $("form").submit(function(){
    var selText = $("#TaskId option:selected").text();
    $("#TaskName").val(selText);           
  });
});

Then in controller you can get

string value = model.TaskName;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.