asp.net-mvc-3 – html.dropdownlist MVC3混乱

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-3 – html.dropdownlist MVC3混乱前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这对我有用,但我如何使用html.dropdownlist做同样的事情?

请注意,传递的值不是向用户显示的值.

@model IEnumerable<MVR.Models.ViewIndividual>

<h2>Level1</h2>    
<select>
        @foreach (var item in Model) {
        <option value="@item.Case_Number">@item.Patient_Lastname,@item.Patient_Firstname
        </option>
}
</select>

解决方法

与ASP.NET MVC应用程序一样,您首先要定义视图模型:
public class Myviewmodel
{
    public string SelectedIndividual { get; set; }
    public SelectList Individuals { get; set; }
}

然后你编写一个控制器动作,从一些数据源或其他东西填充这个视图模型:

public ActionResult Index()
{
    // TODO : fetch those from your repository
    var values = new[]
    {
        new { Value = "1",Text = "item 1" },new { Value = "2",Text = "item 2" },new { Value = "3",Text = "item 3" },};

    var model = new Myviewmodel
    {
        Individuals = new SelectList(values,"Value","Text")
    };
    return View(model);
}

最后你有一个使用强类型助手的强类型视图:

@model Myviewmodel
@Html.DropDownListFor(
    x => x.SelectedIndividual,Model.Individuals
)

这就是说,因为我发现你没有在你的应用程序中使用任何视图模型,你总是可以尝试以下丑陋(不推荐,这需要你自己承担风险):

@model IEnumerable<MVR.Models.ViewIndividual>

<h2>Level1</h2>
@Html.DropDownList(
    "SelectedIndividual",new SelectList(
        Model.Select(
            x => new { 
                Value = x.Case_Number,Text = string.Format(
                    "{0},{1}",x.Patient_Lastname,x.Patient_Firstname
                ) 
            }
        ),"Text"
    )
)

当然,这种色情内容不是我建议在视图中写的东西,我也不会向我最坏的敌人推荐.

结论:在ASP.NET MVC应用程序中,您应始终使用视图模型和强类型帮助程序的强类型视图(请参阅我的答案的第一部分).

原文链接:https://www.f2er.com/aspnet/247476.html

猜你在找的asp.Net相关文章