从ASP.NET MVC中的数据库以表格形式填充下拉列表 [英] Populate dropdownlist from database in asp.net MVC in a form

查看:78
本文介绍了从ASP.NET MVC中的数据库以表格形式填充下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我发现了一些类似的帖子,但没有一点帮助我找不到解决的方法(其他帖子的日期不完整)。

Ok, I found some similar posts, but I don't find a way to solve it without a little help (the other posts have incomplete dates).

我有一个页面需要在其中显示一个下拉列表,其中包含数据库中的值(显示名称,但将键ID保留为值)....此列表,以及表单的其他输入类型。

I have a page where I need to display a dropdownlist with values from database (display Name, but keeping the key Id as value).... this list, with other types of input for a form.

我的模型:

public class AddOfferAnnounceModel
{
    public AnnounceTypeList AnnounceTypeList {get; set; }
    public int Surface { get; set; }
    public int SubTypeId { get; set; }

    [Required]
    public decimal Price { get; set; }

    [StringLength(200, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 0)]
    public string AnnounceDetails { get; set; }

    public bool Net { get; set; }
}

public class AnnounceTypeList
{
    public int SubTypeId { get; set; }
    public string TypeDesc { get; set; }
}

我的控制器[httpGET]操作(可能必须在下拉列表中填充:

My Controller [httpGET] Action (where probably must populate the dropdownlist:

// GET: Announce/Add new announce
    public ActionResult AddOffer()
    {
        string sql = "select typeId, typeDesc from announceTypes where parentTypeId = 1";
        using (SqlConnection cn = new SqlConnection(ConnectionString))
        {
            cn.Open();
            DataTable dt = new DataTable();
            SqlCommand cmd = new SqlCommand(sql, cn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);

            var apartmentTypeList = new List<AnnounceTypeList>();
            foreach (DataRow dr in dt.Rows)
            {
                var apartmentType = new AnnounceTypeList
                {
                    SubTypeId = Convert.ToInt32(dr["TypeId"]),
                    TypeDesc = dr["TypeDesc"].ToString()
                };
                apartmentTypeList.Add(apartmentType);
            }
            return View();
        }
    }

我的控制器[httpPOST]-返回的所有值都在哪里从View和插入数据库的查询

My Controller [httpPOST] - where are all values returned from View and the query to insert into database

[HttpPost]
    public ActionResult AddOffer(AddOfferAnnounceModel model)
    {
        bool isValid = true; // daca datele introduse in formularul anuntului sunt corecte si respecta regulile

        if (isValid)
        {
            string announceDetailsItem = model.AnnounceDetails;
            decimal priceItem = model.Price;
            int surfaceItem = model.Surface;
            int subTypeId = model.SubTypeId; // GETTING FROM DROPDOWNLIST !!!!
            int netItem = Convert.ToInt32(model.Net);
            DateTime dateItem = DateTime.Now;

            string sql = "insert into announces (typeid, statusId, locationId, finalPrice, date, surface, net, announceDetails) values (1, 1, 1, " + priceItem + ",'" + dateItem + "'," + surfaceItem + "," + netItem + ",'" + announceDetailsItem + "')";
                  sql += " insert into announceOfferApartments (announceId, subTypeId, yPersonTypeId) values ((select max(announceId) from announces), 6, 4)";

            using (SqlConnection cn = new SqlConnection(ConnectionString))
            {
                cn.Open();
                SqlCommand cmd = new SqlCommand(sql, cn)
                {
                    CommandType = CommandType.Text
                };
                cmd.ExecuteScalar();
                return RedirectToAction("OfferList", "Announce");
                // daca datele au fost introduse in DB, se redirectioneaza catre Lista Anunturilor
            }
        }
        return OfferList();
    }

我的视图:

@model myApp.com.Models.AddOfferAnnounceModel

。 ..

<div class="form-group">
        @Html.LabelFor(model => model.Price, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Price, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Price, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Surface, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Surface, new { htmlAttributes = new { @class = "form-control" } })
        </div>
    </div>

....

我知道一个视图中不能有多个模型。我知道可能必须创建一个包含所有参数的组合类,但是我不知道如何填充数据表中的列表(或者可能是带有键和值的字典?!?)并在下拉列表中显示值,以及

I know can't have more than one model in a View. I know that probably must create a Combined class which include all parameters, but I don't know how I must to populate a List from DataTable (or maybe a Dictionary with Key and Value ?!?) and display the Value in dropdown, and transfer the key to parameter subTypeId in Controller->ActionResult AddOffer[httpPost].

我需要以相同的形式创建4 5个下拉列表,但是方法可能是相同的....!

I need to create 4 5 dropdownlists in same form, but probably the method will be the same .... !

谢谢,希望不要收到太多否定票:D

thanks, and hope to not receive too many negative votes :D

推荐答案

您实际上需要创建一个View模型,该模型将保存将显示在下拉列表中的数据以及其他数据,这些数据还将通过 HttpPost 。这是要执行的步骤。首先创建一个新类,即View Model:

You actually need to create View Model which will hold the data that will be displayed in the drop down list and other data as well which will get posted back via HttpPost. Here are the steps to. First create a new class which would be View Model:

public class AddOfferViewModel
{

   public AddOfferAnnounceModel Model {get;set;}

   public SelectList AnnouncementTypeSelectList {get;set;}

   public AddOfferViewModel()
   {
       Model = new AddOfferAnnounceModel();
   }

}

,现在在您的添加要约,您将必须组成ViewModel并将其传递给视图:

and now in your Get action of Add Offer you will have to compose the ViewModel and pass it to the View:

// GET: Announce/Add new announce
public ActionResult AddOffer()
{
    string sql = "select typeId, typeDesc from announceTypes where parentTypeId = 1";
    using (SqlConnection cn = new SqlConnection(ConnectionString))
    {
        cn.Open();
        DataTable dt = new DataTable();
        SqlCommand cmd = new SqlCommand(sql, cn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);

        var apartmentTypeList = new List<AnnounceTypeList>();
        foreach (DataRow dr in dt.Rows)
        {
            var apartmentType = new AnnounceTypeList
            {
                SubTypeId = Convert.ToInt32(dr["TypeId"]),
                TypeDesc = dr["TypeDesc"].ToString()
            };
            apartmentTypeList.Add(apartmentType);
        }

         AddOfferViewModel viewModel = new AddOfferViewModel();
         viewModel.AnnouncementTypeSelectList  = new SelectList(apartmentTypeList,"SubTypeId","TypeDesc")
        return View(viewModel);
    }
}

现在,您的视图应使用 AddOfferViewModel

Now your view should be strongly type with the AddOfferViewModel:

@model myApp.com.ViewwModels.AddOfferViewModel
...
<div class="form-group">
        @Html.LabelFor(model => model.Model.Price, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Model.Price, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Model.Price, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Model.Surface, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Model.Surface, new { htmlAttributes = new { @class = "form-control" } })
        </div>
    </div>

现在您可以添加下拉列表,例如:

and now you can add dropdown list like:

@Html.DropDownListFor(model=>model.Model.SubTypeId,Model.Model.AnnouncementTypeSelectList)

您还可以通过其他方式执行此操作,即在ViewModel中添加属性以容纳 List< AnnouncementType> ,然后在View中在 DropDownListFor 方法调用内,创建内联 SelectList

You can also do it other way which would be to add property in ViewModel to hold List<AnnouncementType> and then in View inside the DropDownListFor method call create SelectList inline.

在这种情况下,请替换属性:

In that case, replace property:

public SelectList AnnouncementTypeSelectList {get;set;}

with:

public List<AnnounceTypeList> AnnouncementTypes {get;set;}

,在您的操作中,您只需设置 AnnouncementTypes 现在像:

and in your action, you will just set the AnnouncementTypes now like:

// GET: Announce/Add new announce
public ActionResult AddOffer()
{
    string sql = "select typeId, typeDesc from announceTypes where parentTypeId = 1";
    using (SqlConnection cn = new SqlConnection(ConnectionString))
    {
        cn.Open();
        DataTable dt = new DataTable();
        SqlCommand cmd = new SqlCommand(sql, cn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);

        var apartmentTypeList = new List<AnnounceTypeList>();
        foreach (DataRow dr in dt.Rows)
        {
            var apartmentType = new AnnounceTypeList
            {
                SubTypeId = Convert.ToInt32(dr["TypeId"]),
                TypeDesc = dr["TypeDesc"].ToString()
            };
            apartmentTypeList.Add(apartmentType);
        }

         AddOfferViewModel viewModel = new AddOfferViewModel();
         viewModel.AnnouncementTypes = apartmentTypeList ;
        return View(viewModel);
    }
}

,然后在视图中创建下拉菜单以下行:

and in View for creating dropdown, it will be the following line:

@Html.DropDownListFor(model=>model.Model.SubTypeId,
                            new SelectList(Model.Model.AnnouncementTypes,
                                           "SubTypeId",
                                           "TypeDesc"))

希望有帮助!

这篇关于从ASP.NET MVC中的数据库以表格形式填充下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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