html.dropdownlist MVC3混乱

时间:2011-09-13 22:37:37

标签: asp.net-mvc-3

这对我有用,但我如何使用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>

2 个答案:

答案 0 :(得分:13)

与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
                ) 
            }
        ), 
        "Value", 
        "Text"
    )
)

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

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

答案 1 :(得分:0)

以下是完整示例

  public class PageModel
    {
        [Display(Name = "Page ID")]
        public Guid ID { get; set; }
        [Display(Name = "Page Type ID")]
        public Guid PageTypeID { get; set; }
        [Display(Name = "Title")]
        public string Title { get; set; }
        [Display(Name = "Page Type Name")]
        public string PageTypeName { get; set; }
        [Display(Name = "Html Content")]
        public string HtmlContent { get; set; }
        public SelectList PageTypeList { get; set; }
    }

C#代码

public ActionResult Edit(Guid id)
{
    var model = db.Pages.Where(p => p.ID == id).FirstOrDefault();


    var typeList = new SelectList(db.PageTypes.OrderBy(s => s.Name).ToList(), "ID", "Name");
    var viewModel = new PageModel { PageTypeList = typeList };
    viewModel.HtmlContent = model.HtmlContent;
    viewModel.ID = model.ID;
    viewModel.PageTypeID = Guid.Parse(model.PageTypeID.ToString());
    viewModel.Title = model.Title;


    return View(viewModel);
}

[HttpPost]
[ValidateInput(false)]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(PageModel page)
{
    if (ModelState.IsValid)
    {
        var model = db.Pages.Where(p => p.ID == page.ID).FirstOrDefault();
        model.Title = page.Title;
        model.HtmlContent = page.HtmlContent;
        model.PageTypeID = page.PageTypeID;

        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(page);
}

最后是html

@model competestreet.com.Models.PageModel
@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_LayoutCMS.cshtml";
}
<script type="text/javascript">
    $(document).ready(function () {
        $('#HtmlContent').ckeditor();
    });
</script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/ckeditor/ckeditor.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/ckeditor/adapters/jquery.js")" type="text/javascript"></script>
<h2 class="title">
    <span class="text-cms">CM<span>S</span></span></h2>
<div class="box">
    <div class="t">
    </div>
    <div class="c">
        <div class="content">
            <div class="main-holder">
                <div id="sidebar">
                    <ul>
                        <li><a href="@Url.Content("~/Cms/Index")">Home</a></li>
                        <li><a href="@Url.Content("~/Pages/Index")">Pages</a></li>
                    </ul>
                </div>
                <div id="content" style="min-height: 500px;">
                    @using (Html.BeginForm())
                    {
                        @Html.ValidationSummary(true)
                        <fieldset>
                            <legend>Page Type -  @Html.DropDownListFor(x => x.PageTypeID, Model.PageTypeList)
                             @Html.ValidationMessageFor(model => model.PageTypeID)</legend>
                            <div class="editor-label">
                                @Html.LabelFor(model => model.Title)
                            </div>
                            <div class="editor-field">
                                @Html.EditorFor(model => model.Title, new { @class = "text-box" })
                                @Html.ValidationMessageFor(model => model.Title)
                            </div>
                            <div class="clear">
                            </div>
                            <div class="editor-label">
                                @Html.LabelFor(model => model.HtmlContent)
                            </div>
                            <div class="editor-field">
                                @Html.TextAreaFor(model => model.HtmlContent, new { @name = "Editor1", @class = "Editor1" })
                                @Html.ValidationMessageFor(model => model.HtmlContent)
                            </div>
                            <div class="clear">
                            </div>


                            <p>
                                <input type="submit" value="Save" class="input-btn" />
                            </p>
                        </fieldset>
                    }
                    <div>
                        @Html.ActionLink("Back to List", "Index")
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="b">
    </div>
</div>