如何在asp.net mvc5的dropdownlisfor中创建和绑定所选值? [英] How to create and bind selected value in a dropdownlisfor in asp.net mvc5?

查看:95
本文介绍了如何在asp.net mvc5的dropdownlisfor中创建和绑定所选值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,请所有程序员在此我需要您的帮助:

i搜索并尝试了我在互联网上找到的每个例子,但没有人尝试为我工作。

我想要做的是,我想在注册表单中创建一个dropdownlisfor,以便每个注册为新用户的人都可以从下拉列表中选择他/她的国家。

现在,大多数文章都做比如dropdownlist从数据库中加载项目,但是我不明白你刚刚创建一个应用程序是怎么回事,但他们永远不会告诉你如何写入数据库。

右现在,我对dropdownlist with item的方法是,如果我将一个foreignkey包含到另一个实体中。

请,我需要一个程序员以他自己的理解向我展示我的视图,控制器(获取和发布) )和模型看起来像。请

Hello, please all programmers i need your help in this:
i have searched and tried every example i find on the internet but no one try to work for me.
What i am trying to do is that i want to create a dropdownlisfor in the registration form so that everyone registering as a new user can select his/her country from a dropdownlist.
Now, most articles do say dropdownlist loads items from the database but i don't understand how that is possible in the sence that you are just newly creating an application but they will never tell you how to write to the database.
Right now, the method i have for dropdownlist with item is if i include a foreignkey into another entity.
Please, i need a programmer to show me in his own understanding how my view, controller(get & post) and model will look like. Please

推荐答案

1.在HomeController中添加以下操作方法

1.Add below action method in HomeController
public ActionResult BindWithModel()
{
    List<SelectListItem> items = new List<SelectListItem>();

    items.Add(new SelectListItem 
                { Text = "Select Category", Value = "0", 
                        Selected = true });
    items.Add(new SelectListItem
                { Text = "Beverages", Value = "1" });
    items.Add(new SelectListItem
                { Text = "Condiments", Value = "2" });
    items.Add(new SelectListItem
                { Text = "Confections", Value = "3" });
    items.Add(new SelectListItem
                { Text = "Dairy Products", Value = "4" });
    items.Add(new SelectListItem
                { Text = "Grains/Cereals", Value = "5" });
    items.Add(new SelectListItem
                { Text = "Meat/Poultry", Value = "6" });
    items.Add(new SelectListItem
                { Text = "Produce", Value = "7" });
    items.Add(new SelectListItem
                { Text = "Seafood", Value = "8" });

    var model = new CategoryModel()
    {
        lstCategory = items,
        selected = 1
    };

    return View(model);
}





2.添加以下HTML代码查看



2.Add below HTML code to View

@Html.DropDownListFor(x => x.selected, Model.lstCategory)


这篇关于如何在asp.net mvc5的dropdownlisfor中创建和绑定所选值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆