0

I am binding my DDL with tempdata which is basically all username and userid as shown below.

<div class="form-group">
    @Html.LabelFor(model => model.AssignedTo, "Assigned To : ", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("UserID", TempData["UserList"] as SelectList, htmlAttributes: new { @class = "control-label col-md-2" })
        @Html.ValidationMessageFor(model => model.AssignedTo, "", new { @class = "text-danger" })
    </div>
</div>

In controller I am trying to fetch value like below.

public ActionResult Create(WMTProjects prj)
{
    prj.AssignedTo

where I am getting value as 0, and I was supposed to get corresponding user's userid.

I was all working fine till i changed from

@using (Html.BeginForm("Create", "CreateProjects", FormMethod.Post, new { id = "FormId" }))

to

@using (Html.BeginForm())

and changed my button attributes to

<input type="submit" value="Create" formaction="Create" formmethod="post" class="btn btn-default" />

Not sure what's wrong in this approach.

James Z
  • 12,209
  • 10
  • 24
  • 44
Chethan
  • 298
  • 1
  • 4
  • 17

1 Answers1

1

You are generating a dropdownlist for a property named UserID, not AssignedTo (and changing the @Html.BeginForm() had nothing to do with it)

When you submit the form, there is no name/value pair for AssignedTo, therefore it is set to the default (0 for an int property)

Change your code to generate the dropdownlist to

@Html.DropDownListFor(m => m.AssignedTo, TempData["UserList"] as SelectList, new { @class = "control-label col-md-2" })
  • Thanks Stephen, Its working. I spent all most an hour and didn't get it! – Chethan Mar 09 '18 at 05:10
  • Always use the strongly typed `***For()` methods :) –  Mar 09 '18 at 05:12
  • Sure, So basically, if we want to get the values in controller, it has to be bind'd by model property. Is my understanding correct? (I am new to MVC) – Chethan Mar 09 '18 at 05:54
  • 1
    Yes (although you could of course just read it from the `Request`, but that would be crazy - always strongly bind to your model). –  Mar 09 '18 at 05:57
  • And you really should be using a view model that contains a property `IEnumerable` rather that `TempData`, which is for passing data from one controller method to another, not for passing data to a view - refer [What is ViewModel in MVC?](https://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) and [this Q/A](https://stackoverflow.com/questions/34366305/the-viewdata-item-that-has-the-key-xxx-is-of-type-system-int32-but-must-be-o) for a typical implementation –  Mar 09 '18 at 05:58