简体   繁体   中英

Razor populating drop down list

On my page I want to include a list of members in a drop down list but I am not sure how exactly I could do this.

How would I populate a drop down list with the members that I am passing with the controller?

This is my controller

 //Add Event
            public ActionResult CreateEvent()
            {    
                var members = db.ClubMembers.ToList();
                return View(members);
            }

            //Add Event
            [HttpPost]
public ActionResult CreateEvent(ClubEvent incomingEvent)
            {
                try
                {
                    if (ModelState.IsValid)
                    {
                        using (var db = new UltimateDb())
                        {
                            db.ClubEvents.Add(incomingEvent);
                            db.SaveChanges();
                        }
                        return RedirectToAction("Index");
                    }
                    return View();
                }
                catch
                {
                    return View();
                }
            }

This is the view I will be using

@model ultimateorganiser.Models.ClubEvent

@{
    ViewBag.Title = "CreateEvent";
}

<h2>CreateEvent</h2>

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

    <div class="form-horizontal">
        <h4>ClubEvent</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        @*Event Title*@
        <div class="form-group">
            @Html.LabelFor(model => model.EventTitle, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.EventTitle, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.EventTitle, "", new { @class = "text-danger" })
            </div>
        </div>


        @*Event Description*@
        <div class="form-group">
            @Html.LabelFor(model => model.EventDesc, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.EventDesc, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.EventDesc, "", new { @class = "text-danger" })
            </div>
        </div>

        @*Event Type*@
        <div class="form-group">
            @Html.LabelFor(model => model.eventType, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EnumDropDownListFor(model => model.eventType, htmlAttributes: new { @class = "form-control", @id = "dropdown" })
                @Html.ValidationMessageFor(model => model.eventType, "", new { @class = "text-danger" })
            </div>
        </div>

        @*Add People*@
        @*<div class="form-group">
            Add Members
            <div class="col-md-10">

                Drop Down List of members will go here

            </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>
}

The best way to pass data between views and action methods are view models.We will go that way.

First create a new view model for the create view.

public class CreateEventVm
{
  public string EventDescription {set;get;}
  public List<SelectListItem> Members {set;get;}
  public int MemberId {set;get;}
}

and in your GET action

public ActionResult Create()
{
  var vm = new CreateEventVm();
  var db= new UltimateDb();
  vm.Members =db.Members.Select(s=> new SelectListItem 
                   { Value=s.Id.ToString(),
                     Text = s.Name
                   }).ToList();
  return View(vm);
}

And your create razor view which is strongly typed to our new CreateEventVm

@model CreateEventVm
@using(Html.BeginForm())
{
  <label>Description</label>
  @Html.TextBoxFor(s=>s.EventDescription)
  <label>Member</label>
  @Html.DropDownListFor(s=>s.MemberId,Model.Members,"Select one")
  <input type="submit" />
}

And in your HttpPost action method

[HttpPost]
public ActionResult Create(CreateEventVm model)
{
  if(ModelState.IsValid)
  {
    using (var db = new UltimateDb())
    {
      var event = new ClubEvent();
      event.EventDescription = model.EventDescription;
      //Set other properties also from view model.

      db.ClubEvents.Add(event);
      db.SaveChanges();
    }

    // Redirect to another action after successful save (PRG pattern)
    return RedirectToAction("SavedSuccessfully");
  }
  vm.Members =db.Members.Select(s=> new SelectListItem 
                       { Value=s.Id.ToString(),
                         Text = s.Name
                       }).ToList();
  return View(vm);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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