Tuesday 15 November 2011

MVC Table Remove Rows with Ajax and JQuery and Razor

I've using MVC3 here so this may change with later version and this works for me (many online examples don't seem to work too well when I try them.


Task: Delete a table row, remove the database item and refresh the form without using postback.


Why: Well I have MVC partial view which is used is various forms/pages and posting back would start to get a bit complex as I only want to use the view one with the minimum amount of controller code. And this is easier once you get your head round it.


This examples clears a Locked Record, but you could really use it for anything.


Controller Code



Partial View Code








How it works

The Ajax makes a call to the backend Controller which Clears the Lock via "ClearLock(int id)" which accepts [HttpDelete]

The JQuery OnComplete = "$('#" + @trid + "').remove();" will delete the table row without the need to postback and reload the form.

So you are doing TWO things here, running back end code call via AJAX (which returns nothing) and running JQuery to delete a row from the table.

Notice we set the id of the row using a unquie id from the model.

Enjoy!



1 comment:

  1. What happen if the row is not deleted in the database, and an error occurs?

    ReplyDelete

Comments are welcome, but are moderated and may take a wee while before shown.