반응형

Let’s check how to work with dropdownlists on ASP.NET MVC web applications.

Basically the object you need to bind an object to a dropdownlist is the SelectList. The following overloads are available:

  • public SelectList(IEnumerable items);
  • public SelectList(IEnumerable items, object selectedValue);
  • public SelectList(IEnumerable items, string dataValueField, string dataTextField);
  • public SelectList(IEnumerable items, string dataValueField, string dataTextField, object selectedValue);

How to…

  • Create a new ASP.NET MVC Web application;
  • Right-click on Controller folder and select Add > Controller;
  • Rename it to CityController and click Add. The controller class is created;
  • Let’s write that is going to be our data source. This method builds a SelectList instance based on a generic list of cities;

public class City
{
    public string Name { get; set; }
    public int ID { get; set; }
}

public static SelectList GetCities(int index)
{
    List<City> cities = new List<City>();

    cities.Add(new City() { ID = 1, Name = “Sao Paulo” });
    cities.Add(new City() { ID = 2, Name = “Toronto” });
    cities.Add(new City() { ID = 3, Name = “New York” });
    cities.Add(new City() { ID = 4, Name = “Tokio” });
    cities.Add(new City() { ID = 5, Name = “Paris” });
    cities.Add(new City() { ID = 6, Name = “Lisbon” });

    SelectList selectList = new SelectList(cities, “ID”, “Name”, index);
    return selectList;
}

  • From the Index action method, let’s add the select list object to the ViewData dictionary and request the view to be rendered;

public ActionResult Index()
{
    ViewData["cities"] = GetCities(1);
    return View();
}

  • Right-click on the method you’ve just coded and select Add View;
  • Create a form using the Html helper method BeginForm and add a dropdownlist and a submit button. Your form will be similar to the following:

<% using (Html.BeginForm()) { %>
<%= Html.DropDownList(“lstCity”, ViewData["Cities"] as SelectList) %>
<input type=”submit” value=”Post” />
<% } %>

  • Build and run the application;
  • Navigating to the url http://localhost/City the view will be loaded with a dropdownlist and a submit button;
  • Let’s create now an action method that will handle the post when the user clicks the post button:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(FormCollection forms)
{
    int selectedItem = Convert.ToInt32(forms["lstCity"]);
    ViewData["cities"] = GetCities(selectedItem);
    return View();
}

Selecting a city on the dropdownlist and clicking on post button will raise a request that reaches the Index action method overload on CityController class that accepts a HttpVerb equals Post. In our simple example, the integer variable stores the id of the selected value on the form.

That is the simplest way to load and get the selected value of the dropdownlist.

반응형
반응형

이번에는 VS 2005 의 TOOL 로 개발한 ASP.NET 과 ASP.NET AJAX 을 VS 2008 로 해당 웹사이트를 호출했을때 문제점을 어떻게 처리해야 하는지에 대해서 설명을 하고자 합니다.


1. VS 2005 툴에서 개발한 ASP.NET 2.0 버전을 VS 2008 TOOL 로 호출할 경우!

- VS 2005 툴로 해당 솔류션 파일을 열거나 파일 경로로 ASP.NET 2.0 을 호출할 경우, VS 2008 은 .NET FRAMEWORK 3.5 로 업그래이드를 할 것인지 아래와 같은 이미지로 확인창을 알려줍니다.



이미지를 클릭하면 원본을 보실 수 있습니다.


2. YES 버튼을 선택하고, 만약에 Microsoft AJAX 을 ASP.NET 2.0 에서 개발한 사례가 있으면 3.5 버전으로 UPGRADE 되면서 아래와 같은 경고창이 발생됩니다.


이미지를 클릭하면 원본을 보실 수 있습니다.


이 오류는 System.Web.Extensions Version 1.0.61025.0 을 로드하지 못해서 발생한 경고창입니다.


이미지를 클릭하면 원본을 보실 수 있습니다.


VS 2008 의 에러리스트에서 상세히 보여주고 있죠. 해당 파일 경로는 WEB.CONFIG 의 30번째 라인에 기술된 태그값에 문제가 있다고 지적했고요. 그 부분을 살펴보죠.


3. ASP.NET 2.0 에서 AJAX 을 구현한 Web.Extensions (AJAX) 때문에 오류가 발생되었는데요. WEB.CONFIG 파일에 구버전의 값이 할당되어 수정해야 합니다.


이미지를 클릭하면 원본을 보실 수 있습니다.


기존 ASP.NET 2.0 은 별개로 MS AJAX 을 사용했으며, 3.5 부터는 내장되어 있습니다.

WEB.CONFIG 파일에서 1.0.61025.0 버전을  3.5.0.0 버전으로 변경작업을 하죠.


이미지를 클릭하면 원본을 보실 수 있습니다.



만약에 AJAX Control Toolkit 까지 설치하여 애용을 했다면 약간의 수정 작업이 필요합니다.


이미지를 클릭하면 원본을 보실 수 있습니다.


VS 2008 툴의 디자인 단에서 보면 탭컨테이너가 로드 되지 못한것을 확인할 수 있는데요.

우선 ASP.NET 3.5 버전의 AJAX Control Toolkit 을 다운받으셔서 설치해야 합니다. 이는 http://ajax.asp.net 사이트에서

다운로드를 받으실 수 있습니다.


다운받은 zip 파일은 원하는 폴더에 압축을 풀면 됩니다. 비스타 일경우, 파일의 속성을 선택하여 "Unblock" 을 선택하고 압축을 풀면 되겠습니다.


이제 Visual Studio Toolbox 의 탭을 하나 만드시고, 가져오기를 하여 만들어  Ajax Control Toolkit 을 페이지단에 추가 합니다. 그러면 아래와 같은 화면을 보실 수 있는데요.


이미지를 클릭하면 원본을 보실 수 있습니다.


해당 bin 폴더에 기존의 AjaxContrlToolkit.dll 파일을 새로운 것으로 대체할 것인지를 물어보면 "모든 아이템 적용"을 선택하고  yes 버튼을 선택하면 적용됩니다.


이미지를 클릭하면 원본을 보실 수 있습니다.


html 가서 확인을 하시면 위와 같이 버전이 변경되어 있는것을 확인 하실 수 있습니다.



** 이 뿐만 아니라 다른 부분 또한 .net framework 3.5 에서 새로 나온 컨트롤 및 asp.net 2.0 에서 사용했던 특정 클래스나 네임스페이가 다소 변경된 부분을 정정 할 수도 있습니다.



도움이 되셨는지는 모르겠네요. 처음 접하시는 분들께는 약간의 단비가 될 수 있을까 해서 올린 것이오니 많은 애용 바랍니다.


- 출처 닷넷(.NET) 프로그래머 모임(다음)

반응형

+ Recent posts