如何将自定义视图模型的列表绑定到 dropDownList 并在 ASP.NET MVC 中 POST 后获取所选值?

发布于 2024-09-05 05:16:19 字数 2238 浏览 9 评论 0 原文

我有以下问题。在我的视图模型中,我定义了一些列表属性,如下所示:

public class BasketAndOrderSearchCriteriaViewModel
{
    List<KeyValuePair> currencies;
    public ICollection<KeyValuePair> Currencies
    {
        get
        {
            if (this.currencies == null)
                this.currencies = new List<KeyValuePair>();
            return this.currencies;
        }
    }

    List<KeyValuePair> deliverMethods;
    public ICollection<KeyValuePair> DeliveryMethods
    {
        get
        {
            if (this.deliverMethods == null)
                this.deliverMethods = new List<KeyValuePair>();
            return this.deliverMethods;
        }
    }
 }

该视图模型嵌入到另一个视图模型中:

 public class BasketAndOrderSearchViewModel
 {
    public BasketAndOrderSearchCriteriaViewModel Criteria
    {
        [System.Diagnostics.DebuggerStepThrough]
        get { return this.criteria; }
    }
 }

我使用 2 个操作方法;一个用于 GET,另一个用于 POST:

[HttpGet]
public ActionResult Search(BasketAndOrderSearchViewModel model){...}

[HttpPost]
public ActionResult SubmitSearch(BasketAndOrderSearchViewModel model){...}

在视图中,我通过使用 EditorFor-Html Helper 实现整个视图模型,它不希望自动显示 List 属性的 DropDownList! 1.问题:如何让 EditorFor 显示 DropDownLists?

由于我无法弄清楚如何使用 EditorFor 显示 DropDownLists,所以我使用了 DropDownList Html 帮助器并通过视图模型填充它,如下所示:

    public IEnumerable<SelectListItem> DeliveryMethodAsSelectListItem()
    {
        List<SelectListItem> list = new List<SelectListItem>();
        list.Add(new SelectListItem()
        {
            Selected = true,
            Text = "<Choose Delivery method>",
            Value = "0"
        });
        foreach (var item in this.DeliveryMethods)
        {
            list.Add(new SelectListItem()
            {
                Selected = false,
                Text = item.Value,
                Value = item.Key
            });
        }

        return list;
    }

我的 2. 问题:As你可以看到我将视图模型传递给带有 POST 属性的操作方法! 有没有办法将 DropDownList 的选定值绑定到传递的视图模型? 目前所有 DropDownList 都是空的,选定的值只能通过我的 Request.Form 获取绝对想避免!

我将非常感谢对此的一些想法或提示!

I have following problem. In my view model I defined some list properties as follows:

public class BasketAndOrderSearchCriteriaViewModel
{
    List<KeyValuePair> currencies;
    public ICollection<KeyValuePair> Currencies
    {
        get
        {
            if (this.currencies == null)
                this.currencies = new List<KeyValuePair>();
            return this.currencies;
        }
    }

    List<KeyValuePair> deliverMethods;
    public ICollection<KeyValuePair> DeliveryMethods
    {
        get
        {
            if (this.deliverMethods == null)
                this.deliverMethods = new List<KeyValuePair>();
            return this.deliverMethods;
        }
    }
 }

This view model is embedded in another view model:

 public class BasketAndOrderSearchViewModel
 {
    public BasketAndOrderSearchCriteriaViewModel Criteria
    {
        [System.Diagnostics.DebuggerStepThrough]
        get { return this.criteria; }
    }
 }

I use 2 action methods; one is for the GET and the other for POST:

[HttpGet]
public ActionResult Search(BasketAndOrderSearchViewModel model){...}

[HttpPost]
public ActionResult SubmitSearch(BasketAndOrderSearchViewModel model){...}

In the view I implement the whole view model by using the EditorFor-Html Helper which does not want to automatically display DropDownLists for List properties!
1. Question: How can you let EditorFor display DropDownLists?

Since I could not figure out how to display DropDownLists by using EditorFor, I used the DropDownList Html helper and filled it through the view model as follows:

    public IEnumerable<SelectListItem> DeliveryMethodAsSelectListItem()
    {
        List<SelectListItem> list = new List<SelectListItem>();
        list.Add(new SelectListItem()
        {
            Selected = true,
            Text = "<Choose Delivery method>",
            Value = "0"
        });
        foreach (var item in this.DeliveryMethods)
        {
            list.Add(new SelectListItem()
            {
                Selected = false,
                Text = item.Value,
                Value = item.Key
            });
        }

        return list;
    }

My 2. question: As you can see I pass my view model to the action metho with POST attribute! Is there a way to get the selected value of a DropDownList get binded to the passed view model? At the moment all the DropDownList are empty and the selected value can only be fetched by the Request.Form which I definitely want to avoid!

I would greatly appreciate some ideas or tips on this!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

兮颜 2024-09-12 05:16:21

对于像我这样最近读到这篇文章的人,我建议您从 http://www.asp.net/mvc/tutorials/mvc-music-store-part-1 其中涵盖了这一点以及与 .NET MVC 应用程序相关的大多数常见技术。

无论如何,你的帖子和答案真的很有用(如果我可以投票给你,我会的:)

For those like me that got to this post these days I'd recommend you to fully download the tutorial from http://www.asp.net/mvc/tutorials/mvc-music-store-part-1 which covers this and most of the common techniques related with .NET MVC applications.

Anyway Really usefull your post and answers man (If I could vote you I would :)

大海や 2024-09-12 05:16:21

让我们尝试解决这个问题:

问题 1 的答案:如何让 EditorFor 显示 DropDownList?

当您调用 Html.EditorFor() 时,您可以将额外的 ViewData 值传递给EdiorTemplate 视图:

<%: Html.EditorFor(model => Model.Criteria, new { DeliveryMethods = Model.DeliveryMethods, Currencies = Model.Currencies}) %>

现在,您已在 EditorTemplate 中初始化并使用了 ViewData["DeliveryMethods"]ViewData["Currency"]

在您的 EditorTemplate 中,您需要以某种方式调用这些条目并将其转换为 DropDowns / SelectLists。
假设您有一个 System.Web.Mvc.ViewUserControl 类型的 ascx 文件,您可以执行以下操作:

<%: Html.LabelFor(model => model.DeliveryMethods) %>
<%: Html.DropDownList("SelectedDeliveryMethod", new SelectList(ViewData["DeliveryMethods"] as IEnumerable, "SelectedDeliveryMethod", "Key", "value", Model.SelectedDeliveryMethod)) %>

货币也是如此。

<%: Html.LabelFor(model => model.Currencies) %>
<%: Html.DropDownList("SelectedCurrency", new SelectList(ViewData["Currencies"] as IEnumerable, "SelectedDeliveryMethod", "Key", "value", Model.SelectedCurrency)) %>

此设置将使您的 DeliveryMethodAsSelectListItem() 过时,并且您可以使用任何类型的列表。意味着您不受 KeyValuePairs 的约束。从现在开始,您只需要调整对 Html.DropDownList() 的调用即可。

正如您所看到的,我向您的 BasketAndOrderSearchCriteriaViewModel 引入了一些新属性:

Model.SelectedDeliveryMethod
Model.SelectedCurrency

它们用于存储当前选定的值。

问题 2 的回答:有没有办法将 DropDownList 的选定值绑定到传递的视图模型?

在 EditorFor 模板中,我们传递新创建的 Model.SelectedDeliveryMethodModel.SelectedCurrency 属性作为 SelectedValue 参数(请参阅 DropDownList 扩展方法的第四次重载)。

现在我们已经让视图完成了它的工作:我们如何在 POST 操作中获取当前选定的值?

现在这真的很容易:

[HttpPost]
public ActionResult SubmitSearch(BasketAndOrderSearchViewModel model)
{
    ...
    var selectedDeliveryMethod = model.Criteria.SelectedDeliveryMethod;
    var selectedCurrency model.Criteria.SelectedDeliveryMethod;
    ...
}

注意:我现在没有 IDE 来测试它,但它应该可以解决问题,或者至少告诉您该往哪个方向走。

Let's try to take on this one:

Answer to Question 1: How can you let EditorFor display DropDownLists?

When you call Html.EditorFor() you can pass extra ViewData values to the EdiorTemplate View:

<%: Html.EditorFor(model => Model.Criteria, new { DeliveryMethods = Model.DeliveryMethods, Currencies = Model.Currencies}) %>

Now you have ViewData["DeliveryMethods"] and ViewData["Currencies"] initialized and available inside your EditorTemplate.

In your EditorTemplate you somehow need to call and convert those entries into DropDowns / SelectLists.
Assuming you've got an ascx file of type System.Web.Mvc.ViewUserControl<BasketAndOrderSearchCriteriaViewModel> you could do the following:

<%: Html.LabelFor(model => model.DeliveryMethods) %>
<%: Html.DropDownList("SelectedDeliveryMethod", new SelectList(ViewData["DeliveryMethods"] as IEnumerable, "SelectedDeliveryMethod", "Key", "value", Model.SelectedDeliveryMethod)) %>

Same goes for the Currencies.

<%: Html.LabelFor(model => model.Currencies) %>
<%: Html.DropDownList("SelectedCurrency", new SelectList(ViewData["Currencies"] as IEnumerable, "SelectedDeliveryMethod", "Key", "value", Model.SelectedCurrency)) %>

This setup will make your DeliveryMethodAsSelectListItem() obsolete and you can use any kind of list. Means you are not bound to KeyValuePairs. You'll just need to adjust your call on Html.DropDownList() from now on.

As you can see, I have introduced some new properties to your BasketAndOrderSearchCriteriaViewModel:

Model.SelectedDeliveryMethod
Model.SelectedCurrency

They are used to store the currently selected value.

Answer to Question 2: Is there a way to get the selected value of a DropDownList get binded to the passed view model?

In the EditorFor template we are passing the newly created Model.SelectedDeliveryMethod and Model.SelectedCurrency properties as the SelectedValue Parameter (See 4th Overload of the DropDownList Extension Method).

Now that we have the View doing it's job: How can we get the currently selected value inside the POST Action?

This is really easy now:

[HttpPost]
public ActionResult SubmitSearch(BasketAndOrderSearchViewModel model)
{
    ...
    var selectedDeliveryMethod = model.Criteria.SelectedDeliveryMethod;
    var selectedCurrency model.Criteria.SelectedDeliveryMethod;
    ...
}

Note: I don't have an IDE to test it right now, but it should do the trick or at least show you in which direction to go.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文