简体   繁体   English

ASP.Net MVC 3中的下拉选择

[英]Drop down selection in ASP.Net MVC 3

I am new to asp.net MVC 3. I want to create dropdown for each year, month and day. 我是asp.net MVC 3的新手。我想为每年,每月和每天创建下拉菜单。 I created a helper class that collects common function. 我创建了一个收集通用功能的助手类。 See below. 见下文。

Common 共同

Public Shared Function GetYearsList() As List(Of SelectListItem)

    Dim items As New List(Of SelectListItem)

    For i = -1 To 2500
        Dim item As New SelectListItem

        item.Text = Now.AddYears(i).Year.ToString()
        item.Value = Now.AddYears(i).Year.ToString()

        If i = Now.Year Then
            item.Selected = True
        End If

        items.Add(item)
    Next

    Return items

End Function

In the Controller class. 在Controller类中。

Function Index() As ActionResult

    ViewData("Year") = Command.GetYearsList()
    ViewData("Month") = Command.GetMonthsList()
    ViewData("Day") = Command.GetDaysList()

    Return View()

End Function

In the View page. 在“查看”页面中。

@Html.DropDownList("Year", DirectCast(ViewData("Year"), List(Of SelectListItem)), New With {.onchange = "setDate();"})

But it didnot select current year. 但是它没有选择当前年份。 How can I do to select current year. 如何选择当前年份。 Otherwise has other solution for that? 否则有其他解决方案吗? Thanks all. 谢谢大家

I show what you want but in C#. 我用C#显示你想要的东西。 I think you can easily rewrite it to VB. 我认为您可以轻松地将其重写为VB。

Firs of all, make a view model class for the view. 首先,为视图创建一个视图模型类。

public class SomeViewModel
{
    public SomeViewModel()
    {
        this.Years = new List<int>();

        for (int i = -1; i <= 2500; i++)
        {
            this.Years.Add(DateTime.Now.AddYears(i).Year);
        }

        this.SelectedYear = DateTime.Now.Year;
    }

    public int SelectedYear { set; get; }
    public List<int> Years { set; get; }
}

It has a property that contains the years, and another for the selected one. 它具有一个包含年份的属性,另一个包含所选年份的属性。

Second, make a simple controller method: 其次,制作一个简单的控制器方法:

public ActionResult Index()
{
    var model = new SomeViewModel();

    return View(model);
}

After this, make your strongly typed view: 之后,使您的强类型视图:

@model YourAppNameSpace.ViewModels.SomeViewModel

...

@Html.DropDownListFor(model => model.SelectedYear, new SelectList(Model.Years))

It will make a DropDownList containing the years, and the selected year is the current year. 它将创建一个包含年份的DropDownList,并且所选年份为当前年份。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM