I'm new to AJAX and trying to delete a row in the table without refreshing the whole page. When the button gets clicked the row is succesfully deleted from database, but i get this error:
NullReferenceException: Object reference not set to an instance of an
object.
Meaning the Model is empty. I don't understand how should I fill the model again after AJAX call.
Anybody dealt with this before?
My model class:
public class Person
{
public int PersonId { get; set; }
public string PersonName { get; set; }
public string PersonAddress { get; set; }
}
My Index.cshtml.cs:
[ValidateAntiForgeryToken]
public class IndexModel : PageModel
{
private readonly WebApplication20.Data.ApplicationDbContext _context;
public IndexModel(WebApplication20.Data.ApplicationDbContext context)
{
_context = context;
}
public IList<Models.Person> Person { get;set; }
public async Task OnGetAsync()
{
Person = await _context.Person.ToListAsync();
}
public IActionResult OnPostDeleteById(int id)
{
var pers = _context.Person.Find(id);
_context.Remove(pers);
_context.SaveChanges();
Person = _context.Person.ToList();
return new JsonResult
("Customer Deleted Successfully!");
}
}
My Index.cshtml:
#page
#model WebApplication20.Pages.Person.IndexModel
<p>
<a asp-page="Create">Create New</a>
</p>
<div id="msg"></div>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Person[0].PersonName)
</th>
<th>
#Html.DisplayNameFor(model => model.Person[0].PersonAddress)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Person)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.PersonName)
</td>
<td>
#Html.DisplayFor(modelItem => item.PersonAddress)
</td>
<td>
<form method="post">
<button class="btn btn-danger" onclick="DeleteId('#item.PersonId');">Delete</button>
</form>
</td>
</tr>
}
</tbody>
</table>
Javascript (embed in script tag at bottom of page)
<script>
function DeleteId(id) {
var options = {};
options.url = "/Person/Index?handler=DeleteById&id=" + id;
options.beforeSend = function(xhr) {
xhr.setRequestHeader("MY-XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
};
options.dataType = "json";
options.type = "POST";
options.success = function (data) {
$("#msg").html("Great Success");
};
options.error = function () {
$("#msg").html("Error something went wrong");
};
$.ajax(options);
}
</script>
Related
I'm a bit confused because I thought this a very straight-forward thing, it's possibly something simple tripping me up.
I have a view:
#model IEnumerable<CarViewModel>
#using (Html.BeginForm("SummarySaveAll", "VroomVroom", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div>
<table>
<thead>
<tr>
<th width="1">
#Html.DisplayNameFor(model => model.Driver)
</th>
<th width="1">
#Html.DisplayNameFor(model => model.Colour.Name)
</th>
</tr>
</thead>
<tbody>
#foreach (var element in Model)
{
<tr>
<td width="1">
#Html.DisplayFor(m => element.Driver)
</td>
<td width="1">
#Html.DropDownListFor(m => element.Colour, element.Colours, "Unknown")
</td>
</tr>
}
</tbody>
</table>
<div>
<input type="submit" value="Save Changes" class="btn" />
#Html.ActionLink("Cancel Changes", "Index", null, new { #class = "btn" })
</div>
</div>
}
and the list/enumerable of CarViewModel is supposed to bounce back to the VroomVroom controller, action SummarySaveAll which it does - but the viewmodel on the page doesn't get passed back to it:
[HttpPost]
public ActionResult SummarySaveAll(IEnumerable<CarViewModel> summaries)
{
// Want to do stuff with summaries but it's always null
return View();
}
I tried to encapsulate the List in another ViewModel and cycle through elements using a for i loop but that wouldn't pass back to the controller either.
Surely it's possible to send a List or IEnumerable of models back to a controller?
My CarVM:
public class CarViewModel
{
[MaxLength(150)]
[Display(AutoGenerateField = true, Name = "Entered By")]
public string Driver { get; set; }
[Display(AutoGenerateField = true)]
public Colour Colour { get; set; }
[Key]
[Display(AutoGenerateField = false)]
public int Id { get; set; }
[Display(AutoGenerateField = false)]
public bool IsDeleted { get; set; } = false;
public IEnumerable<SelectListItem> Colours { get; set; }
public CarViewModel() { }
public CarViewModel(Model CarModel summaryModel, CarPropertyCollection propertyCollection)
{
Driver = summaryModel.Driver;
Id = summaryModel.Id;
IsDeleted = summaryModel.IsDeleted;
Colour = summaryModel.Colour == null ? null :
propertyCollection.Colours.Where(x => x.Id == summaryModel.Colour.Id).FirstOrDefault();
Colours = propertyCollection.Colours.Select(x => new SelectListItem { Value = x.Id.ToString(), Text = x.Name });
}
}
}
Must stress that Colour is a custom class but only has Id and Name properties
Colours doesn't relate to a specific car, it relates to cars in general, so rather than using a collection as your view model, create a wrapper:
class EditCarsViewModel
{
public IEnumerable<SelectListItem> Colours { get; set; }
public IList<CarViewModel> Cars { get; set; }
}
Then your view:
#model EditCarsViewModel
#for (int i = 0; i < Model.Cars.Length; i++)
{
<td>
#Html.DropDownListFor(m => Model.Cars[i].Colour, Model.Colours, "Unknown")
</td>
}
Any other CarViewModel properties will need their own input as well. HiddenFor can be used if they should be readonly:
#model EditCarsViewModel
#for (int i = 0; i < Model.Cars.Length; i++)
{
#Html.HiddenFor(m => Model.Cars[i].Id)
#Html.HiddenFor(m => Model.Cars[i].Driver)
<!-- etc. -->
<td>
#Html.DropDownListFor(m => Model.Cars[i].Colour.Id, Model.Colours, "Unknown")
</td>
}
And your controller:
[HttpPost]
public ActionResult SummarySaveAll(EditCarViewModel model)
{
// model.Cars should be populated
return View();
}
Note that an indexable collection, such as IList<T> should be used, as the form field names need to include the index to differentiate the items.
Edit by OP
The Colour class consists of a [Key] int Id property and a string Name property. For DropDownList items I had to make sure the Id property was specified on the m => Model.Cars[i].Colour.Id line otherwise that particular prop was coming back as null even though other items were coming through fine.
try
[HttpPost]
public ActionResult SummarySaveAll(IList<CarViewModel> summaries)
{
// Want to do stuff with summaries but it's always null
return View(summaries);
}
I've also added this model as a param for your view
This how you do it:
First my View which posts back to a controller named Home and an action named ListView:
#model List<MyModel>
#{
ViewData["Title"] = "Using a list as model";
}
<h1>#ViewData["Title"]</h1>
#using (Html.BeginForm("ListView", "Home", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div>
<table>
<thead>
<tr>
<th width="1">
Name
</th>
<th width="1">
Description
</th>
</tr>
</thead>
<tbody>
#for (var i = 0; i < Model.Count; i++)
{
<tr>
<td width="1">
#Html.DisplayFor(m => Model[i].Name)
</td>
<td width="1">
#Html.TextBoxFor(m => Model[i].Description)
</td>
</tr>
}
</tbody>
</table>
<div>
<input type="submit" value="Save Changes" class="btn" />
#Html.ActionLink("Cancel Changes", "Index", null, new { #class = "btn" })
</div>
</div>
}
Notice how I used an indexer to render the controls [i]
This is my model:
public class MyModel
{
public string Name { get; set; }
public string Description { get; set; }
}
This is my controller action:
[HttpPost]
public IActionResult ListView(IEnumerable<MyModel> model)
{
return View(model);
}
And this is the result:
I am using Asp .Net Core 2.2 to create a shopping cart. So, I want to add items on cart when user clicks Add to Cart button. As you can see the below code is working fine. I have checked "mydata" variable is getting all the data but Json.Stringify(data) doesn't passing any data to controller.
$(".addtocart").click(function (event) {
event.preventDefault();
var mydata = {
"CartItemID": $(this).data("pid"),
"Name": $("#name").text(),
"ImageUrl": $("#mainimage").attr("src"),
"Amount": $("#price").val(),
};
$.ajax(
{
url: "/cart/add",
type: "post",
contentType: "application/json",
data: JSON.stringify(mydata)
}
).done(function (addresult) {
$("#cartItemCount").text(addresult.items)
$("#cartItemCountInner").text(result.Items)
});
});
Below is the controller code. Model is showing null:
[HttpPost]
public ActionResult Add(CartItem item)
{
Cart cart = HttpContext.Session.GetObjectFromJson<Cart>("_Cart");
if (cart == null)
cart = new Cart();
cart.Add(item);
HttpContext.Session.SetObjectAsJson("_Cart", cart);
JsonResult result = new JsonResult(new { Items = cart.NumberOfItems });
return result;
}
Please also check the session is used correctly or not because I'm new to Asp .Net Core and don't know much about asp .net core session.
Below is the SessionExtension Code for handling complex object to session:
public static class SessionExtension
{
public static void SetObjectAsJson(this ISession session, string key, object value)
{
session.SetString(key, JsonConvert.SerializeObject(value));
}
public static T GetObjectFromJson<T>(this ISession session, string key)
{
var value = session.GetString(key);
return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
}
}
Here is a working demo like below:
1.Model:
public class CartItem
{
public int CartItemID { get; set; }
public string Name { get; set; }
public string ImageUrl { get; set; }
public int Amount { get; set; }
}
2.View:
#model IEnumerable<CartItem>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.ImageUrl)
</th>
<th>
#Html.DisplayNameFor(model => model.Amount)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
<div id="name">#item.Name</div>
</td>
<td>
<img id="mainimage" src="#item.ImageUrl" />
</td>
<td>
<input id="price" value="#item.Amount" />
</td>
<td>
<input type="button" class="addtocart" data-pid="#item.CartItemID" value="add to cart"/>
</td>
</tr>
}
</tbody>
</table>
#section Scripts
{
<script>
$(".addtocart").click(function (event) {
event.preventDefault();
var mydata = {
"CartItemID": $(this).data("pid"),
"Name": $("#name").text(),
"ImageUrl": $("#mainimage").attr("src"),
"Amount": $("#price").val(),
};
console.log(JSON.stringify(mydata));
$.ajax(
{
url: "/cart/add",
type: "post",
contentType: "application/json",
data: JSON.stringify(mydata)
}
).done(function (addresult) {
$("#cartItemCount").text(addresult.items)
$("#cartItemCountInner").text(result.Items)
});
});
</script>
}
3.Controller(You need to add FromBody to your action):
[HttpPost]
public ActionResult Add([FromBody]CartItem item)
{
//...
}
4.Result:
I create a table in my CSHTML, I want to pass the array of nr of items == aantal back to my controller however this doesn't seem to work. Any idea whats wrong or why I get a null reference in my controller?
CSHTML
#using (Html.BeginForm("OrderConfirm", "Beurs", new { vm = Model.Aantal }, method: FormMethod.Post))
{
<table class="table table-striped table-condensed table-bordered">
<tr>
<th>
Naam
</th>
<th>
Prijs
</th>
<th>
Minimum prijs
</th>
<th>
Factor
</th>
<th> Actie</th>
<!--
<th>Edit</th>-->
</tr>
#foreach (var item in Model.ItemLijstVm)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Naam)
</td>
<td>
€ #Html.DisplayFor(modelItem => item.Prijs)
</td>
<td>
€ #Html.DisplayFor(modelItem => item.MinimumPrijs)
</td>
<td>
#Html.DisplayFor(modelItem => item.Factor)
</td>
<td>
#Html.TextBoxFor(m => m.Aantal[item.Id - 1], new {type = "number" })
</td>
</tr>
}
</table>
<input type="submit" value=" Bevestig bestelling " width="120" />
}
ViewModel
public class BeursLijstViewModel
{
public IEnumerable<BeursItemViewModel> ItemLijstVm{get; set;}
public string Naam { get; set; }
public double Crash { get; set; }
//References naar animated gif
public bool Event { get; set; }
public string GifPath { get; set; }
public int[] Aantal { get; set; }
public int VerhoogAllePrijzen { get; set; }
public double Totaal { get; set; }
public SelectListItem Categorie { get; set; }
public BeursLijstViewModel(Beurs beurs)
{
ItemLijstVm= beurs.Items.Select(g => new BeursItemViewModel(g));
Naam = beurs.Naam;
Aantal = new int[beurs.Items.Count()];
Totaal = beurs.Totaal;
}
}
Controller
[HttpPost]
public ActionResult OrderConfirm(int[] vm) //VM is null but should be array
{
//Some more code
}
The reference I get on my post from my model is null, but if i declare it in my foreach loop like this, it works. I really don't have a clue what goes wrong:
#using (Html.BeginForm("Add", "Beurs", new { id = item.Id, aantal = Model.Aantal }, method: FormMethod.Post))
{
#Html.TextBoxFor(m => m.Aantal[item.Id - 1], new { type = "number" })
<input type="submit" value=" + " width="120"/>
}
I think you have to pass back the actual model not just array expecting to get result, since when it binds it goes several layers like name='Model.item[z]'
[HttpPost]
public ActionResult OrderConfirm(BeursLijstViewModel vm)
{
foreach (var item in vm.ItemLijstVm)
{
var response= vm.Aantal[item.Id - 1]
}
}
#using (Html.BeginForm("OrderConfirm", "Beurs", new { vm = Model.Aantal }, method: FormMethod.Post))
changing the above part in combination with the answer of #COLD TOLD to
#using (Html.BeginForm("OrderConfirm", "Beurs"))
fixed my problem. Thanks for the help!
Below is the Model
public class M_ProjectType
{
public Int16 ProjectTypeID { get; set; }
public String ProjectType { get; set; }
public Boolean IsActive { get; set; }
public Decimal Cost { get; set; }
public String Description { get; set; }
public Boolean IsChecked { get; set; }
}
Below is View Model
public class VM_Project
{
public string[] SkillID { get; set; }
public List<M_ProjectType> ProjectType { get; set; }
}
Below is Get Action method. here I am getting the data for projects that will be sent to View Model
[HttpGet, Route("Project")]
public async Task<ActionResult> Project()
{
var projectTypes = (await _projectTypes.ProjectTypesList()).Value;
var list = new List<M_ProjectType>();
foreach (var item in projectTypes)
{
list.Add(new M_ProjectType
{
Cost = item.Cost,
Description = item.Description,
IsActive = item.IsActive,
IsChecked = false,
ProjectType = item.ProjectType,
ProjectTypeID = item.ProjectTypeID
}
);
}
var project = new VM_Project
{
ProjectType = list
};
return View(project);
}
Below is Razor View
#foreach (var item in Model.ProjectType)
{
<table class="table table-striped">
<tbody>
<input type="hidden" value="#item.ProjectTypeID" name="ProjectTypeID" />
<tr>
<td style="width:5%">
#Html.CheckBoxFor(i => item.IsChecked, new { #class = "tableflat" })
#Html.HiddenFor(i => item.ProjectTypeID)
</td>
<td style="width:10%">#item.ProjectType</td>
<td style="width:80%">#item.Description</td>
<td style="width:5%"><b>$#item.Cost</b></td>
</tr>
</tbody>
</table>
}
Below is Post Action Method
[HttpPost, Route("Project")]
public ActionResult Project(VM_Project project)
{
return View();
}
Question: I am getting project.ProjectType = null. Any suggestion why
this is happening ?
I would recommend using EditorTemplates.
Create a folder named EditorTemplates in you Views/Shared direcotry.
Create a partial view based on your type i.e. M_ProjectType.cshtml
Put your markup that you use in foreach loop in M_ProjectType.cshtml file
#model M_ProjectType
<table class="table table-striped">
<tbody>
<tr>
<td style="width:5%">
#Html.CheckBoxFor(i => i.IsChecked, new { #class = "tableflat" })
#Html.HiddenFor(i => i.ProjectTypeID)
</td>
<td style="width:10%">#Model.ProjectType
#Html.HiddenFor(i=>i.ProjectType)
</td>
<td style="width:80%">#Model.Description</td>
<td style="width:5%"><b>$#Model.Cost</b></td>
</tr>
</tbody>
Then render your editor template in your form like (note: no foreach loop)
#Html.EditorFor(m=>m.ProjectType)
You should get correct model binded to your html elements back in controller.
Try this:
#foreach (var item in Model.ProjectType)
{
<table class="table table-striped">
<tbody>
<tr>
<td style="width:5%">
#Html.CheckBoxFor(i => item.IsChecked, new { #class = "tableflat" })
#Html.HiddenFor(i => item.ProjectTypeID, new { #Value = item.ProjectTypeID})
</td>
</tr>
</tbody>
</table>
}
I am trying to get to get a list box working correctly, which will function very much like this.
The Available exercises are seeded from Migrations/Configuration. I need to be able to add multiples of each exercise from Available to Selected Regime. I am using a view model to access multiple models from another project(User and RegimeItems). However im simply at a loss at what to do next.
Controller.cs
[HttpGet]
public ActionResult Exercise(int? id)
{
User user = db.Users.Find(id);
UserExerciseViewModel model = new UserExerciseViewModel { AvailableExercises = GetAllExercises(), RequestedExercises = new List<RegimeItem>() };
return View(model);
}
//Post
[HttpPost]
public ActionResult Index(UserExerciseViewModel model, string add, string remove, string send, int id)
{
User user = db.Users.Find(id);
//ModelState.Clear();
RestoreSavedState(model);
if (!string.IsNullOrEmpty(add))
AddExercises(model);
else if (!string.IsNullOrEmpty(remove))
SaveState(model);
return View(model);
}
void SaveState(UserExerciseViewModel model)
{
model.SavedRequested = string.Join(",", model.RequestedExercises.Select(p => p.RegimeItemID.ToString()).ToArray());
model.AvailableExercises = GetAllExercises().Except(model.RequestedExercises).ToList();
}
void RemoveExercises(UserExerciseViewModel model)
{
if (model.RequestedSelected != null)
{
model.RequestedExercises.RemoveAll(p => model.RequestedSelected.Contains(p.RegimeItemID));
model.RequestedSelected = null;
}
}
void AddExercises(UserExerciseViewModel model)
{
if (model.AvailableSelected != null)
{
var prods = GetAllExercises().Where(p => model.AvailableSelected.Contains(p.RegimeItemID));
model.RequestedExercises.AddRange(prods);
model.AvailableSelected = null;
}
}
void RestoreSavedState(UserExerciseViewModel model)
{
model.RequestedExercises = new List<RegimeItem>();
//get the previously stored items
if (!string.IsNullOrEmpty(model.SavedRequested))
{
string[] prodids = model.SavedRequested.Split(',');
var prods = GetAllExercises().Where(p => prodids.Contains(p.RegimeItemID.ToString()));
model.RequestedExercises.AddRange(prods);
}
}
public ViewResult Done()
{
return View();
}
public List<RegimeItem> GetAllExercises()
{
var items = db.RegimeItems.ToList();
}
UserExerciseViewModel.cs
namespace FaceToFaceWebsite.Models
{
public class UserExerciseViewModel
{
public List<RegimeItem> AvailableExercises { get; set; }
public List<RegimeItem> RequestedExercises { get; set; }
public int[] AvailableSelected { get; set; }
public int[] RequestedSelected { get; set; }
public string SavedRequested { get; set; }
}
}
Migrations/Configuration.cs
protected override void Seed(FaceToFace.Model.F2FData context)
{
var ahPose = new Pose { Name = "Ah" };
There are lots of other pieces of information that specify the pose/Exercise however its not relevant to the question.
View - Exercise.cs
<%using(Html.BeginForm()){ %>
<div>
<table>
<thead>
<tr>
<th>Available</th>
<th>
</th>
<th>Selected</th>
</tr>
</thead>
<tbody>
<tr>
<td valign="top">
<%=Html.ListBoxFor(model => model.AvailableExercises,
new MultiSelectList(Model.AvailableExercises, "RegimeItemID",
"Name", Model.AvailableSelected))%>
</td>
<td valign="top">
<input type="submit" name="add"
id="add" value=">>" /><br />
<input type="submit" name="remove"
id="remove" value="<<" />
</td>
<td valign="top">
<%=Html.ListBoxFor(model => model.RequestedSelected,
new MultiSelectList(Model.RequestedExercises, "RegimeItemID",
"Name", Model.RequestedSelected))%>
</td>
</tr>
</tbody>
</table>
<br />
<%=Html.HiddenFor(model=>model.SavedRequested) %>
</div>
<%} %>
What i am trying to do is allow exercises to assigned specifically to each user. These excercises have already been seeded. When this works correctly it should allow the exercises to accessed in a descending order.
Update
As per Stephens suggestions i have got the code to at least not throw any errors.
However this an image of what i am receiving on the Exercise page now.
UPDATE 2
As per Stephen's help i have made changes to the Excercise.cshtml view below.
#model FaceToFaceWebsite.Models.UserExerciseViewModel
#using (Html.BeginForm())
{
<div>
<table>
<thead>
<tr>
<th>Available</th>
<th>
</th>
<th>Selected</th>
</tr>
</thead>
<tbody>
<tr>
<td valign="top">
#Html.ListBoxFor(model => model.AvailableExercises, new MultiSelectList(Model.AvailableExercises, "RegimeItemID", "RegimeExercise", Model.AvailableSelected))
</td>
<td valign="top">
<input type="submit" name="add"
id="add" value=">>" /><br />
<input type="submit" name="remove"
id="remove" value="<<" />
</td>
<td valign="top">
#Html.ListBoxFor(model => model.RequestedSelected, new MultiSelectList(Model.RequestedExercises, "RegimeItemID", "RegimeExercise", Model.RequestedSelected))
</td>
</tr>
</tbody>
</table>
<br />
#Html.HiddenFor(model => model.SavedRequested)
</div>
}
I am now getting this as the listbox shown in the image below.
I am not sure if this problem resides in site.css however its more likely that it's not finding the exercises that have been seeded.
As per Stephens help i was able to get it to work, on the other hand it appears that im using one of the models incorrectly.Stephen has provided the information that got me to a error-less build, regardless of my failings before i posted the question. The final issue is not with css as mentioned in the comments, well it might be but the problem before that is that the are multiple models i need to use to get the exercises to show.
This is the viewmodel.
namespace FaceToFaceWebsite.Models
{
public class UserExerciseViewModel
{
public List<RegimeItem> AvailableExercises { get; set; }
public List<RegimeItem> RequestedExercises { get; set; }
public int[] AvailableSelected { get; set; }
public int[] RequestedSelected { get; set; }
public string SavedRequested { get; set; }
}
}
Controller.cs
//GET
[HttpGet]
public ActionResult Exercise(int? id)
{
User user = db.Users.Find(id);
UserExerciseViewModel model = new UserExerciseViewModel { AvailableExercises = GetAllExercises(), RequestedExercises = new List<RegimeItem>() };
return View(model);
}
//Post
[HttpPost]
public ActionResult Index(UserExerciseViewModel model, string add, string remove, string send, int id)
{
User user = db.Users.Find(id);
//ModelState.Clear();
RestoreSavedState(model);
if (!string.IsNullOrEmpty(add))
AddExercises(model);
else if (!string.IsNullOrEmpty(remove))
SaveState(model);
return View(model);
}
void SaveState(UserExerciseViewModel model)
{
model.SavedRequested = string.Join(",", model.RequestedExercises.Select(p => p.RegimeItemID.ToString()).ToArray());
model.AvailableExercises = GetAllExercises().Except(model.RequestedExercises).ToList();
}
void RemoveExercises(UserExerciseViewModel model)
{
if (model.RequestedSelected != null)
{
model.RequestedExercises.RemoveAll(p => model.RequestedSelected.Contains(p.RegimeItemID));
model.RequestedSelected = null;
}
}
void AddExercises(UserExerciseViewModel model)
{
if (model.AvailableSelected != null)
{
var prods = GetAllExercises().Where(p => model.AvailableSelected.Contains(p.RegimeItemID));
model.RequestedExercises.AddRange(prods);
model.AvailableSelected = null;
}
}
void RestoreSavedState(UserExerciseViewModel model)
{
model.RequestedExercises = new List<RegimeItem>();
//get the previously stored items
if (!string.IsNullOrEmpty(model.SavedRequested))
{
string[] prodids = model.SavedRequested.Split(',');
var prods = GetAllExercises().Where(p => prodids.Contains(p.RegimeItemID.ToString()));
model.RequestedExercises.AddRange(prods);
}
}
public ViewResult Done()
{
return View();
}
private List<RegimeItem> GetAllExercises()
{
return db.RegimeItems.ToList();
}
and the View.
#model FaceToFaceWebsite.Models.UserExerciseViewModel
#using (Html.BeginForm())
{
<div>
<table>
<thead>
<tr>
<th>Available</th>
<th>
</th>
<th>Selected</th>
</tr>
</thead>
<tbody>
<tr>
<td valign="top">
#Html.ListBoxFor(model => model.AvailableExercises, new MultiSelectList(Model.AvailableExercises, "RegimeItemID", "RegimeExercise", Model.AvailableSelected))
</td>
<td valign="top">
<input type="submit" name="add"
id="add" value=">>" /><br />
<input type="submit" name="remove"
id="remove" value="<<" />
</td>
<td valign="top">
#Html.ListBoxFor(model => model.RequestedSelected, new MultiSelectList(Model.RequestedExercises, "RegimeItemID", "RegimeExercise", Model.RequestedSelected))
</td>
</tr>
</tbody>
</table>
<br />
#Html.HiddenFor(model => model.SavedRequested)
</div>
}