Reputation: 10484
In my MVC4 application I have two models being User
and Schedule
that look like this:
public class User {
public int UserId { get; set; }
public string Name { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
public bool isAvailable { get; set; }
}
public class Schedule
{
public int ScheduleId{ get; set; }
public DateTime Date { get; set; }
public int UserId { get; set; }
public virtual User User { get; set; }
}
Now I want to make a page that will display a table with the days of this month and next to the day a DropDownLists
(per day) with all the users with isAvailable
to true in the list. This page will be used so that an admin can make a schedule (I would also be open for improvements on how to implement this) and select one user per weekday. I want to make it so that once a user is selected in one DropDownList
that this user disappears from the other DropDownLists
.
The Controller and View looks as follows now, controller:
public ActionResult Schedule()
{
ViewBag.UserId = new SelectList(db.Users, "UserId", "FullName");
return View();
}
View:
@model IEnumerable<seashell_brawl_corvee.Models.Schedule>
@{
ViewBag.Title = "Schedule";
}
<fieldset>
<legend>@ViewBag.Title</legend>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<table class="table">
<thead>
<tr>
<th>Date
</th>
<th>Select person
</th>
</tr>
</thead>
@{ DateTime dt = DateTime.Now; }
@for (double i = 0.0; i < 60.0; i++)
{
dt = dt.AddDays(1);
if (dt.Date.DayOfWeek != DayOfWeek.Saturday &&
dt.Date.DayOfWeek != DayOfWeek.Sunday)
{
<tbody>
<tr>
<td>
@dt.Date.ToLongDateString()
</td>
<td>
@Html.DropDownList("UserId", String.Empty)
</td>
</tr>
</tbody>
}
else
{
<tbody>
<tr></tr>
</tbody>
}
}
</table>
@TODO: Submit button and controller POST action that reads the dates and names
from the dropdownlists, puts them into arrays and then into the database.
}
</fieldset>
I know I need JavaScript/JSON to make the DropDownLists dependent on each other and have names no longer displayed once they are selected, but I do not know how exactly I would go to accomplish this. I would be very grateful if someone could help me further!
Upvotes: 3
Views: 339
Reputation: 823
I have an approach using JQuery, Check this example: http://jsfiddle.net/vt3Ma/4/
using focus() event will restore the current option value and text in 2 hidden fields
$('.ddl').focus(function(){
$("#oldValue").val($(this).val());
$("#oldText").val($("option:selected",$(this)).text());
});
then on change() event:-
1- will add the old changed option of the dropdown list to the other dropdown lists as the previous selected option became available now to choose.
$(this).prepend("<option value='"+$("#oldValue").val()+"'>"+$("#oldText").val()+"</option>");
2- will remove the new selected option from all other dropdown lists
$("option[value='" + current.val() + "']",$(this)).remove();
Upvotes: 2