ASP.NET MVC - 帮助改进mvc下拉框的代码? [英] ASP.NET MVC - Help needed to Improve the code for mvc's Drop-Down Box?

查看:65
本文介绍了ASP.NET MVC - 帮助改进mvc下拉框的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了下面的下拉列表来填充城市列表。



一切正常,但我想知道更好的方法请。另外,如果可以使用<创建相同的下拉菜单,请告诉我。选择>而不是HTML助手。



以下是我的DTO课程。请告知我是否可以对控制器和视图进行改进。



(我相当初学者,并没有达到使用存储库的概念模式还有)非常感谢任何帮助 - 谢谢。

  //   ViewModel  

public class LocationDTO
{
public IEnumerable< CityDTO>城市{获取; set ; }
public LocationDTO()
{
this .Cities = new CityDTO [] {};
}
}

public class CityDTO
{
public string CityId {获得; set ; }
public string CityName { get ; set ; }

}



下面是我的Controller,我使用了实体框架数据库的第一种方法来获取数据来自数据库。您能否解决我需要在控制器上进行的改进?

  //  控制器 

Models.LocationDTO Loc = new Models.LocationDTO();
EF.LocationEntities locCtx = new EF.LocationEntities();

public 行动结果索引(){
使用(locCtx ){
var locResults =( from q in locCtx.usp_GetAllCities()
选择 new Models.CityDTO {
CityId = q.Id,
CityName = q.Name});
loc.Cities = locResults.ToList();
}

列表< Models.CityDTO> citiesList = new 列表< Models.CityDTO>();
Models.CityDTO city = new Models.CityDTO(){CityId = - 1,CityName = 选择城市} ;
citiesList.Add(city);
citiesList.AddRange(Loc.Cities.ToList());

ViewBag.CitiesDropDown = citiesList;
return view(loc);
}



以下是我的观点。我也想知道Lamdba表达式在这种情况下是如何工作的。

 //查看
@ {
List < TestApp.Models.CityDTO > citiesList = ViewBag.CitiesDropDown;
var cityItems = new SelectList(citiesList,CityId,CityName);
}
< div >
城市:@ Html.DropDownListFor(x => x.Cities.SingleOrDefault()。CityID,@ cityItems)
< / div >

解决方案

您好,



请尝试以下代码



 [HttpGet] 
public ActionResult Index()
{
ViewBag.CitiesDropDown = GetCityList ();
return View();
}


私人列表< selectlistitem> GetCityList()
{
// 您可以在此处访问数据库以获取所需数据。只需确保返回类型
列表< selectlistitem> itemList = new 列表< selectlistitem>();
itemList.Add( new SelectListItem {Text = City1,值= 1,Selected = true });
itemList.Add( new SelectListItem {Text = City2,值= 2});
itemList.Add( new SelectListItem {Text = City3,值= 3});
return itemList;
}



然后在你的视图中



 @ Html.DropDownList(City_Code,ViewBag.CitiesDropDown作为List <   selectlistitem  > ,)<   / selectlistitem  >  







希望这会简化你:)


有几种方法可以做到这一点。你甚至不需要使用ViewBag。

请查看我最近的文章:动态表格输入在ASP.NET MVC3中进行无阻碍验证 [ ^ ](:))。它也涵盖了这种情况。

SelectListItem 在你动态生成元素时非常有用,已选择,但由于同一个类可用于填充列表框,并且你启用了多选,而不是在多个元素中将多个属性设置为true也是可行的。 / blockquote>

创建一个类DropdownList< t>其中T是包含值的属性的实体,文本和方法如下所示



  public   static   class  DropDownList< T> 
{
public static SelectList LoadItems(IList< T> collection, string value string text)
{
return new SelectList(collection, value ,text);
}

}





调用如下方法。第一个参数是IEnumerable的集合您需要在下拉列表中填充的记录和剩余参数是值字段和文本字段。

 ViewData [  LoadCities] = DropDownList< City> .LoadItems(_requestRepository.GetCities(), < span class =code-string> Id,  City); 





从以下视图拨打电话



@ Html.DropDownListFor(型号=> model.Id,(IEnumerable< selectlistitem>)ViewData [LoadCities], - Select - ,new {@class =select})



您可以重复使用DropDownList来填充下拉列表。希望这有助于


I have created the below drop-down to populate a list of cities.

All works fine, but I would like to know the better ways of doing this please. Also, please let me know if it is possible to create the same drop down using < Select > instead of HTML helpers.

Below are my DTO classes. Please advise if I can make improvements in the controller and the view as well.

(I am fairly a beginner, and haven''t reached the concepts of using repository patterns yet) Any help would be greatly appreciated - thanks.

//ViewModel

 public class LocationDTO
    {
        public IEnumerable<CityDTO> Cities { get; set; }
        public LocationDTO()
        {
            this.Cities = new CityDTO[] { };
        }
    }

 public class CityDTO
    {
        public string CityId { get; set; }
        public string CityName { get; set; }

    }


Below is my Controller, and I''ve used entity framework database first approach to get the data back from database. Could you please address the improvements that needs to be done on my controller ?

//Controller

Models.LocationDTO Loc = new Models.LocationDTO();
EF.LocationEntities locCtx = new EF.LocationEntities();

public Action Result Index() {
                    using(locCtx) {
    var locResults    = (from q in locCtx.usp_GetAllCities()
                       Select new Models.CityDTO {
                       CityId = q.Id,
                       CityName = q.Name  });
    loc.Cities = locResults.ToList();
    }

List<Models.CityDTO> citiesList = new List<Models.CityDTO>();
Models.CityDTO city = new Models.CityDTO() { CityId = "-1", CityName = "Select City" };
                      citiesList.Add(city);
                      citiesList.AddRange(Loc.Cities.ToList());

ViewBag.CitiesDropDown = citiesList;
return view(loc);
}


Below is my View. I''d also like to know how the Lamdba expression works in this scenario please.

//View
@{
    List<TestApp.Models.CityDTO> citiesList = ViewBag.CitiesDropDown;
    var cityItems = new SelectList(citiesList, "CityId", "CityName");
}
<div>
    Cities: @Html.DropDownListFor(x => x.Cities.SingleOrDefault().CityID, @cityItems)
</div>

解决方案

Hi,

Try the following code

[HttpGet]
public ActionResult Index()
{
     ViewBag.CitiesDropDown = GetCityList();
     return View();
}


private List<selectlistitem> GetCityList()
{
     //Here you can access DB to get your required data. Just make sure the return type
     List<selectlistitem> itemList = new List<selectlistitem>();
     itemList.Add(new SelectListItem { Text = "City1", Value = "1", Selected = true });
     itemList.Add(new SelectListItem { Text = "City2", Value = "2" });
     itemList.Add(new SelectListItem { Text = "City3", Value = "3" });
     return itemList;
}


and then in your view

@Html.DropDownList("City_Code", ViewBag.CitiesDropDown as List<selectlistitem>, "")</selectlistitem>




Hope this simplifies you :)


You have several ways to do this. You don''t even need to use ViewBag.
Please look at my recent article: Dynamic tabular input with unobstructive validation in ASP.NET MVC3[^] (:)). It covers this scenario also.
SelectListItem is useful if you generate your element on the fly, Selected has to be set only at one single item if you have dropdown, but as the same class can be used to fill a listbox, and you enable multiselect, than setting multiple this property to true at multiple elements is also viable.


Create a class DropdownList<t> where T is the entity which contain the property for value and text and method like below

public static class DropDownList<T>
   {
       public static SelectList LoadItems(IList<T> collection, string value, string text)
       {
           return new SelectList(collection, value, text);
       }
      
   }



Call the method like below.First Argument is the IEnumerable collection of records that you need to populate in the dropdown and remaining arguments are the value field and text field.

ViewData["LoadCities"] = DropDownList<City>.LoadItems(_requestRepository.GetCities(),"Id","City");



Call from the view like below

@Html.DropDownListFor(model => model.Id, (IEnumerable<selectlistitem>)ViewData["LoadCities"], "--Select--", new { @class = "select" })

You can reuse the DropDownList to pulate the dropdown list.Hope this helps


这篇关于ASP.NET MVC - 帮助改进mvc下拉框的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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