如何访问asp.net mvc中的选择值下拉列表?

时间:2015-12-31 04:38:12

标签: asp.net-mvc razor asp.net-mvc-5

我是ASP.net MVC和Razor的新手。

我想使用下拉列表保存用户生日,但我不知道如何访问控制器中的选定值。 在此之前我使用TextBoxFor它不适合从用户获取日期。 我读了很多类似的问题,但我不明白。

我的Register.cshtml的一部分:

 <div class="form-group">
        <label class="label">BirthDate</label>
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.UserBirthDate)
            @Html.ValidationMessageFor(model => model.UserBirthDate)            
            <select name="Year">
                <option value="2000">2000</option>
                <option value="2001">2001</option>
                <option value="2002">2002</option>
                <option value="2003">2003</option>
                <option value="2004">2004</option>
                <option value="2005">2005</option>
                <option value="2006">2006</option>
            </select>
            <select name="Month">
                <option value="7">July</option>
                <option value="9">September</option>
                <option value="12">December</option>
            </select>
            <select name="Day">
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>
            </select>
        </div>
    </div>

我的控制器的一部分:

[HttpPost]
    public ActionResult Register(User user)
    {

        UserRepositories bluser = new UserRepositories();

        if (ModelState.IsValid)
        {
            if(user.UserBirthDate != null)
            {
               /////
            }

            if (bluser.Add(user))
            {

                return MessageBox.Show("Succsess", MessageType.Success);
            }
            else
            {

                return MessageBox.Show(" UNSuccsess", MessageType.Error);
            }
        }
        else
        {


            return MessageBox.Show(ModelState.GetErrors(), MessageType.Warning);
        }

    }

用户模型:

public partial class User
{
    public int UserID { get; set; }
    public string UserEmail { get; set; }
    public string UserFirstName { get; set; }
    public string UserLastName { get; set; }
    public string UserPassWord { get; set; }
    public string UserCellPhone { get; set; }
    public string UserTell { get; set; }
    public string UserImage { get; set; }
    public string UserAddress { get; set; }
    public Nullable<byte> UserStatus { get; set; }
    public Nullable<System.DateTime> UserBirthDate { get; set; }
    public string UserGender { get; set; }
}

usermetaData.cs

internal class UserMetaData
{
    [ScaffoldColumn(false)]
    [Bindable(false)]
    public int UserID { get; set; }

    public string UserEmail { get; set; }


    public string UserFirstName { get; set; }


    public string UserLastName { get; set; }


    [DataType(DataType.Password)]
    public string UserPassWord { get; set; }

    public string UserCellPhone { get; set; }


    public string UserTell { get; set; }

    public string UserImage { get; set; }
    public string UserAddress { get; set; }


    public Nullable<byte> UserStatus { get; set; }

    public Nullable<System.DateTime> UserBirthDate { get; set; }


    public string UserGender { get; set; }
}
 }
namespace NP1.Models
{
[MetadataType(typeof(NP1.Models.MetaData.UserMetaData))]
public partial class User
{

    public string UserConfirmPassWord { get; set; }

    public string Year { get; set; }
    public string Month { get; set; }
    public string Day { get; set; }
}

2 个答案:

答案 0 :(得分:2)

正如David在评论中建议的那样,您应该考虑使用java脚本日期选择器库(例如:JQuery UI,Bootstrap等..)来设置大多数用户都熟悉的UI日期。日期下拉似乎有点老了! :(

如果您仍想在问题中使用下拉菜单,则应为视图创建视图模型,并为所有选定的选项值添加3个属性。

public class CreateUserVm
{
    public int Year { set; get; }
    public int Month { set; get; }
    public int Day{ set; get; }
    public string UserEmail { set; get; }
    pubic string UserFirstName  {set;get;}
    //Add other properties as needed
}

在您的GET操作中,您将向您的视图发送此对象,

public IActionResult Index()
{
  return View(new CreateUserVm());
}

您的视图强烈输入此视图模型

@model YourNameSpaceHere.CreateUserVm
<form asp-action="Index" asp-controller="Home" enctype="multipart/form-data">
        <label class="label">BirthDate</label>
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.UserEmail)
            @Html.TextBoxFor(s=>s.UserFirstName)                
            <select name="Year">
                <option value="2000">2000</option>
                <option value="2001">2001</option>                   
            </select>
            <select name="Month">
                <option value="7">July</option>
                <option value="12">December</option>
            </select>
            <select name="Day">
                <option value="1">1</option>
                <option value="2">2</option>                   
            </select>
        </div>
    <input type="submit" />
</form>

只要您的select元素的name属性值与我们在视图模型中的属性名称匹配,MVC模型绑定就会在提交表单时将表单数据映射到视图模型的对象。 / p>

[HttpPost]
public IActionResult Index(CreateUserVm model)
{
    if (ModelState.IsValid)
    {
      var bluser = new UserRepositories();
      //read the model.Year and model.UserName etc and create a user entity here
       //to do :Save and return something
        User u = new User { UserEmail= model.UserEmail};
        u.UserFirstName = model.UserFirstName ;  
        // Set other properties also.     
        bluser.Add(u);
    }
    return View(logos);
}

如果您想在编辑操作方法中为下拉列表设置所选选项,请查看this answer.

答案 1 :(得分:1)

您可以通过以下方式更改ViewModel:

public class UserVM
{
   public string Year { set; get; }
   public string Month { set; get; }
   public string Day{ set; get; }
   // other properties
}

然后在你的action方法中你可以填充这些属性:

[HttpGet]
public ActionResult Register(User user)
{
     // It should be better to read this data from database
     ViewBag.Year = new SelectList(
                                    new List<SelectListItem>
                                    {
                                        new SelectListItem { Text = "1368", Value = "1987" },
                                        new SelectListItem { Text = "1369", Value = "1988"}, //....
                                    }, "Value" , "Text");
    // Also other properties like Month and Day
     return View();
}

然后在你的视图中:

@model ProjectName.VM
@using (Html.BeginForm())
{
    <div class="form-group">
        @Html.DropDownListFor(m => m.Year, (SelectList)ViewBag.Year, "Select one")
    </div>

    <button type="Submit" class="btn btn-success submit">Send</button>
}

最后发布数据的操作方法:

    [HttpPost]
    public ActionResult Register(VM model) 
    {
        if(!ModelState.IsValid) {}
        var Year = model.Year;
        // Here you can get other data like Day, Month
        // rest of your code for saving the data

        return View();
    }

dotnetfiddle