ASP.NET MVC下拉列表选项

时间:2013-04-28 10:52:49

标签: asp.net-mvc html.dropdownlistfor

我的索引页面上有一个DropDownListFor,我的创建页面中有一个。两个下拉列表都有相同的用途。

我想要的是当用户在索引页面的索引下拉列表中选择一个项目时,它会将所选项目的值保存为会话的GUID,并且创建< / strong>页面加载,我希望其中的下拉列表根据会话中的GUID选择项目。

当用户点击“创建”并转到创建页面时,我只是设置一个对象并将该对象发送到创建视图。

修改

我通过这样做将用户发送到“创建”页面:

Html.ActionLink("Create New Listing", "Create", null, new { @class = "btn btn-primary" }))

如何将选定项目的GUID发送到视图?

2 个答案:

答案 0 :(得分:1)

如果您想使用Session,我认为您需要使用表单发布到ActionResult以保存下拉列表的值,然后重定向到“创建”页面。

public ActionResult SaveGuid(Guid value)
{
    Session["SelectedGuid"] = value;
    return new RedirectResult("Create");
}

然后在Create ActionResult中,将Session值传递给Create View的Model。

public ActionResult Create()
{
    var selectedGuid = (Guid)Session["SelectedGuid"];
    return View(new CreateViewModel { SelectedGuid = selectedGuid, /* include other properties */ };
}

在您的视图中,您可以在传递给DropDownListFor ...

的SelectList上设置所选选项
@Html.DropDownListFor(
    x => x.SelectedGuid, 
    new SelectList(Model.ListOfStuff, "Key", "Value", Model.SelectedGuid)
)

答案 1 :(得分:1)

我猜你有这样的情况。这是索引视图:

@model Models.IndexViewModel
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
@using (Html.BeginForm("SaveGuid", "Flow"))
{
    Html.DropDownListFor(x => x.SelectedGuid, Model.Guids, new { onchange = "this.form.submit();" });
}

这是索引模型:

public class IndexViewModel
{
    public Guid SelectedGuid { get; set; }
    public SelectList Guids { get; set; }
}

Index和SaveGuid Action看起来像这样:

private List<Guid> Guids = new List<Guid> { Guid.NewGuid(), Guid.NewGuid() }; // for testing only

public ActionResult Index()
{
    var model = new IndexViewModel { Guids = new SelectList(Guids, Guids.First()) };
    return View(model);
}

public ActionResult SaveGuid(IndexViewModel model)
{
    Session["SelectedGuid"] = model.SelectedGuid;        
    return new RedirectResult("Create");
}

创建视图看起来像这样......

@model MvcBootStrapApp.Models.CreateViewModel
@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>
@using (Html.BeginForm("SaveGuid", "Flow"))
{
    @Html.DropDownListFor(x => x.SelectedGuid, Model.Guids, new { onchange = "this.form.submit();" });
}

@using (Html.BeginForm("SaveCreate", "Flow"))
{ 
    // setup other controls
    <input type="submit" value="Submit" />
}

使用像这样的CreateViewModel ......

public class CreateViewModel
{
    public Guid SelectedGuid { get; set; }
    public SelectList Guids { get; set; }

    // include other model properties
}

Create和CreateSave ActionResults看起来像这样......

public ActionResult Create()
{
    Guid selectedGuid = Guids.First();
    if (Session["SelectedGuid"] != null)
        selectedGuid = (Guid)Session["SelectedGuid"];

    return View(new CreateViewModel
    {
        Guids = new SelectList(Guids, selectedGuid),
        SelectedGuid = selectedGuid
    });
}

public ActionResult SaveCreate(CreateViewModel model)
{
    // save properties

    return new RedirectResult("Index");
}

我使用了两种形式来允许更改所选的Guid并回发所有的Create属性。