0

I am getting null value by selecting dropdownlist item in controller.[I saw by doing in debug mode]

Here is my code

Controller

public ActionResult Index()
{
    var jobStatusList = new SelectList(new[] 
    {
        new { ID = "1", Name = "Full Time" },
        new { ID = "2", Name = "Part Time" },
    },
    "ID", "Name", 1);

    ViewData["JobStatusList"] = jobStatusList;
}

public ActionResult Create(StaffRegistrationViewModel staffRegistrationViewModel)
{
    //Here is my code
}

View

@using (Html.BeginForm("Create", "StaffRegistration", FormMethod.Post, new { enctype = "multipart/form-data" }))
{   
    @Html.AntiForgeryToken()
    @Html.DropDownList("jobStatusList",ViewData["JobStatusList"] as SelectList)
}

In staffRegistrationViewModel getting null value in Status field.

Thank You

1 Answer 1

1

Your current code is rendering a dropdown element with name attribute value jobStatusList. If your view models property name is Status it will not be mapped by the model binder because the names do not match.

You need to render a SELECT element with the name Status

@Html.DropDownList("Status", ViewData["JobStatusList"] as SelectList)

But if you are already using a view model, i would recommend adding a property of type List<SelectListItem> to pass the data instead of using ViewData/ViewBag along with the DropDownListFor helper method.

@model StaffRegistrationViewModel 
@using (Html.BeginForm("Create", "StaffRegistration"))
{
   @Html.DropDownListFor(a=>a.Status,Model.StatusList)
}

Assuming your view model has a StatusList proeprty

public class StaffRegistrationViewModel 
{
   public int Status { set;get;}
   public List<SelectListItem> StatusList { set;get;}
}

and your GET action loaded the list to this property

public ActionResult Index()
{
    var list = new List<SelectListItem>
    {
        new SelectListItem {Value = "1", Text = "Full Time"},
        new SelectListItem {Value = "2", Text = "Part Time"}
    };
    var vm=new StaffRegistrationVm { StatusList=list };
    return View(vm);
}
Sign up to request clarification or add additional context in comments.

1 Comment

can you provide me that List<SelectListItem> syntax that how I can adding property and call the view dropdownlist.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.