I’m using ASP.NET MVC 4 with the Razor view engine. I’m trying to remove an item from my webgrid by removing an item from the model in my view. The model in my view looks like this:
@model List<MiscCommon.Entities.Person>
And my attempt to remove an item from this list, via javascript, has failed:
function RemovePerson(personId) {
alert(personId); // Test. This works.
//var people = '@Model[0].FirstName'; // This is a string. I want the actual model.
@foreach(var person in Model)
{
if (person.Id == @:personId) { // Remove row here }
}
}
Within that javascript function, I get the correct ID of the person. How can I remove it from the model? (I’m hoping that my webgrid will update when the row is removed from the model.)
The model for a view is processed when it is executed on the server. It has no direct correlation with the JavaScript that is later executed on the client. You can mix/match Razor expressions within your JS (as you are doing), but JS won’t know anything about the model as an object (unless you tell it).
If you are trying to manipulate a set of IDs, you could do this many ways:
add a data-* attribute to each row of a table that contains the ID of the object.
create a JS array declaration using Razor which contains your list of IDs. When the view is rendered, the array declaration will be rendered.
hidden field(s) that contain data you need
AJAX action links
If you really want the whole model on the client, you could serialize it as a JSON string to a hidden field or as an object literal inside a script block. There’s usually a better way, however.
You can also look at Knockout, which (in my opinion) places more emphasis on the client model. It’s not necessary to solve this problem, though.