0

我的Index页面上有一个 DropDownListFor ,我的Create页面上有一个。两个下拉列表的目的相同。

我想要的是当用户在索引页面的索引下拉列表中选择一个项目时,它将所选项目的值保存到会话的 GUID 并且当创建页面加载时,我希望那里的下拉列表选择基于项目在会话中的 GUID 上。

在用户单击“创建”并进入创建页面的那一刻,我只是设置一个对象并将该对象发送到创建视图。

编辑

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

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

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

4

2 回答 2

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 操作如下所示:

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 属性。

于 2013-04-28T12:25:29.880 回答
1

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

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

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

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)
)
于 2013-04-28T11:19:41.540 回答