For my first ASP.NET MVC 3 application I have a div on a partial view that displays a list of proposed names for a particular ice cream. I’m using, as my first crack at this, something like this to display the proposed names:
@model ViewModels.IceCream.{ProposedNamesViewModel
<table>
<tr>
<th></th>
<th>Proposed Names</th>
</tr>
@foreach (var item in Model.ProposedNames)
{
<tr>
<td>
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
<td>
@item.ProposedName
</td>
</tr>
}
</table>
and this works fine enough for displaying those names. These proposed names are but but one of a number of pieces of information about the selected ice cream and what I’d like to accomplish is to allow the user to add or delete a name and then have as a result of one of those actions have the updated viewmodel’s data re-displayed in that div (i.e., leaving everything else as it is on the page and just replacing that div’s contents with the new contents.
I can write the controller’s delete action just fine and it will update the underlying DB but then I’m not sure how to return this PartialView back to the particular div with my updated viewmodel. I hope that makes sense.
This (likely web developer 101) concept is one that I haven’t grokked yet and I’m hoping someone can show me how to do this.
Update
I’m looking at using jquery to solve this. Stephan Prodan (I believe that’s his name) has an example here where he updates a list of notes using jquery.
JQuery is definitely a good direction to go with this. The only modification I would suggest to your table for a jQuery solution would be to add an index to each < tr > tag (unique for each row, preferably one based off the item displayed in the row). Then the rest is javascript. Bind a click event to the delete option, and on the delete, one jQuery line will do your job:
As far as adding new rows, simply generate a string representing it:
And (now I realize you might want to add an id to your < table > as well if you have more than one on your page) then add it to the table with
or
if it’s your first table on your page and you don’t want to give it an id.
Lastly, you would need an AJAX call to get the information for the new item (or to send it to the backend if you create it on the page).
EDIT:
Suggested AJAX call:
The disabling of the input prevents the user from providing multiple sucessive calls to the db that might conflict with each other or otherwise cause problems.