简体   繁体   中英

MVC: How can I make sure that my field have the value selected inside my view on the edit form?

I am using MVC3-Viewmodel on my project.

I have a create and edit form, What I am trying to do is to make sure that after a user Create a form, he/she should be able to edit it, when the user is at the edit page I want the values to be displayed in the inputs and selects. The only field that is not working is my DropDownList. I have no idea why.

If I close the application and go to the edit form I want that the DropDownList have the value that was created.

here is the code:

foreach (SelectedQuestionViewModel items in Model.AllSelectedQuestions)
{  

 <select id="selectstyle2" class="Grade">
 @{
  <option>n/a</option>
  int Grade = 1;
    for (int i = 1; i <= 10; i++)
    {
     <option @(items.Grade.HasValue && items.Grade.Value == Grade ? "selected" : "") >@(i)</option>
    }
  }
 </select>
}

any help kind of help is appreciated.

note: I use a ajax post to my controller, inside the controller I fill my "Model.Grade" with the value that was selected from this DDL.

You have your select tag within your foreach loop. Write this tag outside, like this:

<select>
@foreach(var x in Model)
   //write out options
</select>

also have a look at Html.DropDownList extension method. This does what you're trying to do by hand.

http://msdn.microsoft.com/en-us/library/system.web.mvc.html.selectextensions.dropdownlist.aspx

as an example

@{
    var selectListItems = (new[] { 1,2,3}).Select(i=>new SelectListItem { Text = i.ToString(), Value = i.ToString() });
}
@Html.DropDownListFor(m=>m.AllSelectedQuestions[0].Grade, selectListItems, "n/a")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM