0

我有一个 HTML 下拉列表:

<select name="status">  
       <option value="close" >Close Task</option>
       <option value="open" >Reopen Task</option>
  </select>

我想根据视图模型中的“Task.Completion”属性设置“选定”选项:

public class TaskEditViewModel
{
    public Task Task { get; set; }
    public TaskComment TaskComment { get; set; }
}

因此,如果 Task.Completion 为 NULL,则选择“关闭”选项,否则选择“打开”选项。

我怎样才能做到这一点?

4

1 回答 1

0

Your view model doesn't seem adapted to what you are trying to do in the view (which according to your question is show a dropdown list and preselect a value based on some property on your view model).

So a far more realistic view model would be this:

public class TaskEditViewModel
{
    public string Completion { get; set; }
    public IEnumerable<SelectListItem> Actions 
    { 
        get
        {
            return new[]
            {
                new SelectListItem { Value = "close", Text = "Close Task" },
                new SelectListItem { Value = "open", Text = "Reopen Task" },
            };
        }
    }
}

then you could have a controller action which will populate and pass this view model to the view:

public ActionResult Foo()
{
    var model = new TaskEditViewModel();

    // this will automatically preselect the second item in the list
    model.Completion = "open";

    return View(model);
}

and finally inside your strongly typed view you could use the DropDownListFor helper to render this dropdown:

@model TaskEditViewModel
@Html.DropDownListFor(x => x.Completion, Model.Actions)
于 2012-01-03T17:00:02.607 回答