MVC5下拉列表选择的项目

时间:2014-10-22 09:40:32

标签: model-view-controller

我想要一个包含3个值的下拉列表(超级用户-admin-user)这是角色

这是我的模特:

 public class LogIn
{
    public int ID { get; set; }
    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [Display(Name = " username")]
    public string userame { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = " password")]
    public string password { get; set; }
    public string role { get; set; }
}

这是我的观点(create.cshtml):

@using (Html.BeginForm()) 
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>LogIn</h4>
    <hr />
    @Html.ValidationSummary(true)

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

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

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

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
}

这是我的LogInController:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using MVCSports.Models;

namespace MVCSports.Controllers
{
public class LogInController : Controller
{
    private LogInDBContext db = new LogInDBContext();

    // GET: /LogIn/
    public ActionResult Index()
    {
        var list = new List<SelectListItem>
                   {
                       new SelectListItem { Text = "Admin", Value = "1" },
                       new SelectListItem { Text = "User", Value = "2" },
                       new SelectListItem { Text = "Someone else", Value = "3" }
                   };
        ViewBag.Roles = list;
        return View(db.sports.ToList());
    }
 // GET: /LogIn/Create
    public ActionResult Create()
    {
        return View();
    }

    // POST: /LogIn/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include="ID,userame,password,role")] LogIn login)
    {
        if (ModelState.IsValid)
        {
            db.sports.Add(login);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(login);
    }

这是index.cshtml:

@model IEnumerable<MVCSports.Models.LogIn>

@{
ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
@Html.ActionLink("Log In", "Create")
</p>

该角色不应该是一个文本字段,它应该是上面三个值的下拉列表,所选的值将保存在数据库中。这可能吗?

1 个答案:

答案 0 :(得分:0)

首先,当您第一次显示“登录”页面时,有些方法需要为下拉列表准备值,因此在ActionResult方法(而不是HttpPost !!)中,您将拥有:

var list = new List<SelectListItem>
                       {
                           new SelectListItem { Text = "Admin", Value = "1" },
                           new SelectListItem { Text = "User", Value = "2" },
                           new SelectListItem { Text = "Someone else", Value = "3" }
                       }; 
ViewBag.Roles = list;

然后在你看来你会有:

 <div class="form-group">
    @Html.LabelFor(model => model.role, new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(model => model.role, (IEnumerable<SelectListItem>)ViewBag.Roles)
        @Html.ValidationMessageFor(model => model.role)
    </div>
</div>

此代码将在视图中显示带有选项和用户答案的​​下拉列表将保存到模型中的角色字段。