填充和ASP.NET选择下拉列表值MVC 4 [英] Populating and Selecting a Drop Down List Value in ASP.NET MVC 4

查看:92
本文介绍了填充和ASP.NET选择下拉列表值MVC 4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下拉在ASP.NET MVC名单让我困惑。我有一个模型类。该模型类有一个叫做SelectedValue的字符串。此字符串再presents是previously选择的值。我有我已经从数据库中抽取项目的集合。集合的每个项目都有一个ID和一个名称值。我的问题是,我不知道得到这个信息到用户界面的推荐的方法是什么。

Drop down lists in ASP.NET MVC confuse me. I have a model class. The model class has a string called SelectedValue. This string represents that previously selected value. I have a collection of items I've pulled from the database. Each item of the collection has an ID and a Name value. My problem is, I don't know what the recommended way of getting this information into the UI is.

我不知道我是否应该使用ViewBag或模型。一旦价值是存在的,虽然,我甚至不能确定填充UI的最佳方式是什么。我见过使用剃刀语法HTML辅助和人民。我很困惑。什么人建议?

I'm not sure if I should use the ViewBag or the Model. Once the value is there though, I'm not even sure what the best way to populate the UI is. I've seen HTML helpers and people using RAZOR syntax. I'm very confused. What do people recommend?

感谢您

推荐答案

这是我如何做到这一点,可以说你有2个型号球队和球员

This is how i do it, lets say you have 2 models Team and Player:

Player.cs

public class Player
{
    [HiddenInput(DisplayValue = false)]
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }        

    [Required]
    [ForeignKey("Team")]
    [Display(Name = "Team")]
    public int TeamId { get; set; }        

    [Display(Name = "First name")]
    public string FirstName { get; set; }

    [Display(Name = "Last name")]
    public string LastName { get; set; }

    public virtual Team Team { get; set; }        
}

Team.cs

 public class Team
{
    [Key]
    [HiddenInput(DisplayValue = false)]
    public int TeamId { get; set; }

    [Display(Name = "Full Name:")]
    public string Name { get; set; }        

    public virtual ICollection<Player> Players { get; set; }
}

在您的PlayerController那么:
注意:团队存在的必要创建一个播放器

Then in your PlayerController: Note: team need to exist to create a player

    private void PopulateTeamsDropDownList(object selectedTeams = null)
    {
        var teamsQuery = from d in _dataSource.Teams
                         orderby d.Name
                         select d;
        ViewBag.TeamID = new SelectList(teamsQuery, "TeamId", "Name", selectedTeams);
    }

    [HttpGet]
    public ActionResult Create()
    {
        PopulateTeamsDropDownList();
        return View();
    }

    [HttpPost]
    public ActionResult Create(Player model)
    {
        if (ModelState.IsValid)
        {
            using (EFootballDb db = new EFootballDb())
            {
                try
                {
                    var player = new Player
                                     {
                                         FirstName = model.FirstName,
                                         LastName = model.LastName
                                     };
                    db.Players.Add(player);
                    db.SaveChanges();
                    return RedirectToAction("About", "Home");
                }
                catch (Exception)
                {
                    ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
                }
            }
        }
        PopulateTeamsDropDownList(model.TeamId);
        return View(model);
    }

和最后的创建视图的玩家应该是这样的:

And lastly your Create View for Player would look like this:

@{
ViewBag.Title = "Create";
 }

<h2>Create</h2>

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)

<fieldset>
    <legend>Player</legend>

    <div class="editor-label">
            @Html.LabelFor(model => model.TeamId, "Pick Your Team")
    </div>
    <div class="editor-field">
        @Html.DropDownList("TeamId", String.Empty)
        @Html.ValidationMessageFor(model => model.TeamId)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.FirstName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.FirstName)
        @Html.ValidationMessageFor(model => model.FirstName)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.LastName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.LastName)
        @Html.ValidationMessageFor(model => model.LastName)
    </div>        

    <p>
        <input type="submit" value="Create" />
    </p>
  </fieldset>
 }

 <div>
     @Html.ActionLink("Back to List", "Index")
 </div>

 @section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

这篇关于填充和ASP.NET选择下拉列表值MVC 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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