I am using a ViewModel to retrieve entered data in controller action. But the ViewModel is getting empty values in it's properties. I am creating one partial view
and in that partial view I am creating drop down lists by binding the ViewModel and then I'm rendering that partial view in other View
Below is my code
My ViewModel :
public class LookUpViewModel
{
RosterManagementEntities rosterManagementContext = new RosterManagementEntities();
public LookUpViewModel()
{
tblCurrentLocations = from o in rosterManagementContext.tblCurrentLocations select o;
tblStreams = from o in rosterManagementContext.tblStreams select o;
}
[Required]
public virtual IEnumerable<tblCurrentLocation> tblCurrentLocations { get; set; }
[Required]
public virtual IEnumerable<tblStream> tblStreams { get; set; }
My Partial View:
@model PITCRoster.ViewModel.LookUpViewModel
@Html.Label("Location")
@Html.DropDownListFor(M=>M.tblCurrentLocations, new SelectList(Model.tblCurrentLocations, "LocationId", "Location"), "Select Location")
@Html.ValidationMessageFor(M=>M.tblCurrentLocations)
<br />
@Html.Label("Stream")
@Html.DropDownListFor(M => M.tblStreams, new SelectList(Model.tblStreams, "StreamId", "Stream"), "Select Streams")
@Html.ValidationMessageFor(M => M.tblStreams)
My View in which I am rendering this above partial view
@{
ViewBag.Title = "Resources";
}
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<h2>Resources</h2>
@using (Html.BeginForm("AddResource", "Resources", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
Html.RenderPartial("_LookUpDropDowns", new PITCRoster.ViewModel.LookUpViewModel());
<br />
<input type="submit" value="Create" />
}
And this is my controller action method : [HttpPost]
public void AddResource(LookUpViewModel testName)
{
//code
}
When I put a debugger on my controller action method control goes to that Action method. But ViewModel object has null in it. I tried accessing entered values using FormCollection object and I'm getting all the data as expected...
Below is my code for controller action with FormCollection
[HttpPost]
public void AddResource(FormCollection form)
{
var x = form["tblStreams"]; //I get value here..
}
Can anybody explain me why I'm not getting values in ViewModel object ? Thank you...
<select>
only posts back a single value (the value of the selected option). Your view model requires properties to bind to - e.g.public int SelectedLocation { get; set; }
and ditto for the selected Stream – user3559349tblCurrentLocations
and 'tblStreams'. Also you drop downs are assigning the selected value to the same list you populate in the view model constructor – 3dd