Reputation: 774
I have a drop down that builds a list using related data from an SQL table (with linq and MVC5, ASP.NET etc). Currently my drop down is like this in the contoller:
ViewData["TeamList"] = new SelectList(db.Players.Select(p => p.Team).Distinct(), TeamFilter);
and the view looks like this:
<span class="pull-right searchDD" id="TeamDD">Team: @Html.DropDownList("TeamList", "-All-")</span>
I want to add a choice at the top of the list that says "Add New" and that choice will call my "Create" Action for the Team controller. HOw would I do this? Is it possible?
I thought perhaps I could build a list with the DB data, then add an ADD NEW option to the start of this list like :
List<SelectItemList> TeamList = new List<selectItemList>();
TeamList.Add(new SelectListItem { Text = "Add NEW", Value = "99" });
foreach(var team in db.Players.Select(p => p.Team).Distinct())
{ TeamList.Add{ Text = team.Name, Value= team.id };}
THEN use Jquery to nmonitor for a value of 99 being selected on the Dropdown, and load a Create Controller Action from there, but that seems super tedious and code-intensive.
Is there an easier way? If not, how do I load a Controller/Action from JQUERY (I can SO search that too)....
Upvotes: 1
Views: 1037
Reputation: 4387
In short, I would advise not to. You're asking to do something like this:
First, how will you know a user selected that option since it's the first one? You'll need to add yet another option above it (blank, or a placeholder).
Second, this is not a great design--it's not intuitive to a user, they have to click the dropdown to even see they can add a new team. What if they don't click it and therefore had no idea they could add a team?
Third, you said it best yourself, it's adds a lot of unnecessary code! Bunch of JS to handle something HTML can do for this natively.
Let's switch to using a Bootstrap input group and make it easier for them:
<div class="row">
<div class="col-xs-4">
<div class="form-group">
<label class="control-label">Teams</label>
<span class="input-group">
<select class="form-control">
<option>Team 1</option>
<option>Team 2</option>
</select>
<span class="input-group-btn">
<a class="btn btn-primary" href="@Url.Action('Create', 'Team')">Add Team</a>
</span>
</span>
</div>
</div>
</div>
I'm still not 100% sure I like this either since it kinda implies you're adding the selected team to something. I might just opt to separate the button from the <select>
element afterall. Up to you!
Notice how I'm also leveraging the ASP.NET MVC HtmlHelper
@Url.Action()
to provide a link to your create team action/controller.
Live example: https://jsfiddle.net/4pxp7r3w/
Upvotes: 1