I have a page that lists records from a database call. I want to have an 'edit' link on each row that will popup a Jquery dialog so that the row can be edited. My question is how do I pass the data from the selected row to the jquery dialog box so that it can be edited?
I'm not sure of your specific requirements (minimizing requests, etc), but you should consider having the edit as another controller action. The jquery dialog will then simply load the controller action in that window (I was doing this with thickbox but now use jqModal).
If you don't want to incur the extra request, there is a sliding scale of three alternatives:
- Have an event on the link that takes some data (might be stored in the link, or somewhere else on the page) and builds the popup window (creating text fields, etc).
- Have an event on the link and a hidden empty form. The event shows the form and populates the form elements.
- Have an event on the link and a form for each list item. The event then only has to show the form.
if you're not going to go with the extra request, I suggest #2.
EDIT:
To go with the "extra request", this is what I do (did -- I'll use thickbox as it's easier):
- Install thickbox (and jquery)
- Create a link to the Edit action with ActionLink() and specify the id and thickbox class. It should end up looking something like <a class="thickbox" href="/Controller/Edit/5">
- Copy the Site.Master template and remove all the HTML header stuff.
Create the Edit action and view. Within the controller, set the master page, like:
return View("viewname", "~/Views/Shared/Inline_page"); // (where Inline_Page is your copy of Site.Master)
Now when you click on the link, thickbox opens up the "window" and loads the href in the link, thus loading the action.
For debugging, right-click on the link and "open in new window" -- thickbox doesn't like error messages or html headers.
After the Edit action is finished doing updates (ie, after the POST), it should redirect back to your list (this has the added benefit of preventing a reload from submitting the form a second time).
For extra credit, you can replace the Inline_Page reference with null when thickbox isn't used (i modified thickbox to pass a &tb=1 querystring). In this case, should javascript not work, the page will work as normal.
James
As James mentioned, there are many options. For one, you could embed the ID of the record inside the 'edit' link ():
<a class="edit" href="/edit" rel="23456">Edit</a>
Then you can have something like this in your JS:
$('a.edit').click(function(e){
e.preventDefault();
var id = $(this).attr('rel');
// 1. show the dialog and get new value(s) from user
// 2. save new info by calling the backend with $.ajax,
// passing in ID and new values
});