This may sound simple but i am stuck up at a very strange problem.
I have created dropdown's in my application and i am not able to fetch the selected value On Edit.
Here is my View:
<div class="editor-field">
@Html.DropDownListFor(model => model.Hobbyhome.HobbyHomeAddressList.First().ProvincialState.ProvincialStateID, new SelectList(ViewBag.State, "ProvincialStateID", "ProvincialStateName"), "-----Select State-----", new { @id = "State" })<font color="red">*</font>
</div>
i have written a function in controller to fetch the value and i am also able to fetch the value but when it goes in View it doesnot show me the value
i have created another dropdown like this:
@Html.DropDownListFor(model => model.Hobbydetail.Hobbymaster.HobbyId, new SelectList(ViewBag.Hobby, "HobbyId", "HobbyName"), "----Select Hobby----", new { @id = "Hobby" })<font color="red">*</font>
And the strange thing is i can see the value of the second dropdown but not for first One
What i think is maybe because i am using an list.First() in the first dropdown and so it isgiving this problem bcoz On edit view page it only shows me "-----Select State--" as value for first dropdown.
Please Help me
To get the "selected value object" in you edit view :
To have all elements in your DropDown, be sure that your ViewBag.Hobby is initialized and filled in your controller before showing Edit view!
First()
method returns the first element of a sequence. It will throw you an exception if the source sequence is empty.Why you need to use First() there ? I think you are doing it in the wrong way. your first paramenter of
DropDownListFor
should be a variable which holds the selected value, in this purticular overload you are using.You should be using the second approach
I would make a clean ViewModel to handle this. This makes my Views Clean.
In the GET action method, Instead of returning the data in ViewBag, I would return it in the ViewModel.
And in the View,
Now you will have the selected value available in your httppost mehod in the SelectedHobbyId property