Posted on June 8th, 2011
Using a simulated dialog window is a nice way to handle inline data editing. The jQuery UI has a UI widget for a dialog window that makes it easy to get up and running with it in your application. With the release of ASP.NET MVC 3, Microsoft included the jQuery UI scripts and files in the MVC 3 project templates for Visual Studio. With the release of the MVC 3 Tools Update, Microsoft implemented the inclusion of those with NuGet as packages. That means we can get up and running using the latest version of the jQuery UI with minimal effort. To the code!
If you are starting with a new MVC 3 application and have the Tools Update then you are a NuGet update and a and
tag away from adding the jQuery UI to your project. If you are using an existing MVC project you can still get the jQuery UI library added to your project via NuGet and then add the link and script tags. Assuming that you have pulled down the latest version (at the time of this publish it was 1.8.13) you can add the following link and script tags to your
tag:
The jQuery UI library relies upon the CSS scripts and some image files to handle rendering of its widgets (you can choose a different theme or role your own if you like). Adding these to the stock _Layout.cshtml
file results in the following markup:
@ViewBag.Title
@RenderBody()
Our example will involve building a list of notes with an id, title and description. Each note can be edited and new notes can be added. The user will never have to leave the single page of notes to manage the note data. The add and edit forms will be delivered in a jQuery UI dialog widget and the note list content will get reloaded via an AJAX call after each change to the list.
To begin, we need to craft a model and a data management class. We will do this so we can simulate data storage and get a feel for the workflow of the user experience. The first class named Note
will have properties to represent our data model.
namespace Website.Models
{
public class Note
{
public int Id { get; set; }
public string Title { get; set; }
public string Body { get; set; }
}
}
The second class named NoteManager
will be used to set up our simulated data storage and provide methods for querying and updating the data. We will take a look at the class content as a whole and then walk through each method after.
using System.Collections.ObjectModel;
using System.Linq;
using System.Web;
namespace Website.Models
{
public class NoteManager
{
public Collection Notes
{
get
{
if(HttpRuntime.Cache["Notes"] == null)
this.loadInitialData();
return (Collection)HttpRuntime.Cache["Notes"];
}
}
private void loadInitialData()
{
var notes = new Collection();
notes.Add(new Note
{
Id = 1,
Title = "Set DVR for Sunday",
Body = "Don't forget to record Game of Thrones!"
});
notes.Add(new Note
{
Id = 2,
Title = "Read MVC article",
Body = "Check out the new iwantmymvc.com post"
});
notes.Add(new Note
{
Id = 3,
Title = "Pick up kid",
Body = "Daughter out of school at 1:30pm on Thursday. Don't forget!"
});
notes.Add(new Note
{
Id = 4,
Title = "Paint",
Body = "Finish the 2nd coat in the bathroom"
});
HttpRuntime.Cache["Notes"] = notes;
}
public Collection GetAll()
{
return Notes;
}
public Note GetById(int id)
{
return Notes.Where(i => i.Id == id).FirstOrDefault();
}
public int Save(Note item)
{
if (item.Id <= 0)
return saveAsNew(item);
var existingNote = Notes.Where(i => i.Id == item.Id).FirstOrDefault();
existingNote.Title = item.Title;
existingNote.Body = item.Body;
return existingNote.Id;
}
private int saveAsNew(Note item)
{
item.Id = Notes.Count + 1;
Notes.Add(item);
return item.Id;
}
}
}
The class has a property named Notes
that is read only and handles instantiating a collection of Note
objects in the runtime cache if it doesn't exist, and then returns the collection from the cache. This property is there to give us a simulated storage so that we didn't have to add a full blown database (beyond the scope of this post). The private method loadInitialData
handles pre-filling the collection of Note
objects with some initial data and stuffs them into the cache. Both of these chunks of code would be refactored out with a move to a real means of data storage.
The GetAll
and GetById
methods access our simulated data storage to return all of our notes or a specific note by id. The Save
method takes in a Note
object, checks to see if it has an Id
less than or equal to zero (we assume that an Id
that is not greater than zero represents a note that is new) and if so, calls the private method saveAsNew
. If the Note
item sent in has an Id
, the code finds that Note
in the simulated storage, updates the Title
and Description
, and returns the Id
value. The saveAsNew
method sets the Id
, adds it to the simulated storage, and returns the Id
value. The increment of the Id
is simulated here by getting the current count of the note collection and adding 1 to it. The setting of the Id
is the only other chunk of code that would be refactored out when moving to a different data storage approach.
With our model and data manager code in place we can turn our attention to the controller and views. We can do all of our work in a single controller. If we use a HomeController
, we can add an action method named Index
that will return our main view. An action method named List
will get all of our Note
objects from our manager and return a partial view. We will use some jQuery to make an AJAX call to that action method and update our main view with the partial view content returned. Since the jQuery AJAX call will cache the call to the content in Internet Explorer by default (a setting in jQuery), we will decorate the List
, Create
and Edit
action methods with the OutputCache
attribute and a duration of 0. This will send the no-cache flag back in the header of the content to the browser and jQuery will pick that up and not cache the AJAX call.
The Create
action method instantiates a new Note
model object and returns a partial view, specifying the NoteForm.cshtml
view file and passing in the model. The NoteForm
view is used for the add and edit functionality. The Edit
action method takes in the Id
of the note to be edited, loads the Note
model object based on that Id
, and does the same return of the partial view as the Create
method. The Save
method takes in the posted Note
object and sends it to the manager to save. It is decorated with the HttpPost
attribute to ensure that it will only be available via a POST. It returns a Json
object with a property named Success
that can be used by the UX to verify everything went well (we won't use that in our example). Both the add and edit actions in the UX will post to the Save
action method, allowing us to reduce the amount of unique jQuery we need to write in our view.
The contents of the HomeController.cs
file:
using System.Web.Mvc;
using Website.Models;
namespace Website.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[OutputCache(Duration = 0)]
public ActionResult List()
{
var manager = new NoteManager();
var model = manager.GetAll();
return PartialView(model);
}
[OutputCache(Duration = 0)]
public ActionResult Create()
{
var model = new Note();
return PartialView("NoteForm", model);
}
[OutputCache(Duration = 0)]
public ActionResult Edit(int id)
{
var manager = new NoteManager();
var model = manager.GetById(id);
return PartialView("NoteForm", model);
}
[HttpPost]
public JsonResult Save(Note note)
{
var manager = new NoteManager();
var noteId = manager.Save(note);
return Json(new { Success = noteId > 0 });
}
}
}
The view for the note form, NoteForm.cshtml
, looks like so:
@model Website.Models.Note
@using(Html.BeginForm("Save", "Home", FormMethod.Post, new { id = "NoteForm" })) {
@Html.Hidden("Id")
}
It is a strongly typed view for our Note
model class. We give the element an
id
attribute so that we can reference it via jQuery. The and
tags give our UX some structure that we can style with some CSS.
The List.cshtml
view is used to render out a
element with all of our notes.
@model IEnumerable
@foreach (var note in Model)
{
-
@note.Title
@note.Body
Edit
}
This view is strongly typed as well. It includes a tag that we will use as an edit button. We add a custom attribute named
noteid
to the tag that we can use in our jQuery to identify the
Id
of the note object we want to edit.
The view, Index.cshtml
, contains a bit of html block structure and all of our jQuery logic code.
@{
ViewBag.Title = "Index";
}
Notes
Add New Note
The The jQuery document load block contains the setup for the dialog node, click event bindings for the edit and add links, and a call to a JavaScript function called The The click event binding for the add link is similar to the edit, only we don't need to get the id value and we load the Finally, we toss in some CSS in the With all of our code in place we can do an F5 and see our list of notes: If we click on an edit link we will get the dialog widget with the correct note data loaded: And if we click on the add new note link we will get the dialog widget with the empty form: The end result of our solution tree for our sample: I am going to try something new and provide the sample solution for this post. Note that you will need to have Visual Studio 2010 and the MVC 3 Tools Update to run this solution. Please let me know if you do download it and encounter any weirdness so I can refine the process and make these available going forward. Enjoy!id
attribute of "NoteListBlock" is used as a container target for the load of the partial view content of our List
action method. It starts out empty and will get loaded with content via jQuery once the DOM is loaded. The id
attribute of "NoteDialog" is the element for our dialog widget. The jQuery UI library will use the title
attribute for the text in the dialog widget top header bar. We start out with it empty here and will dynamically change the text via jQuery based on the request to either add or edit a note. This display:none
style on the element. Since our call to the jQuery UI method to make the element a dialog widget will occur in the jQuery document ready code block, the end user will see the display:hidden
to the LoadList
that handles the AJAX call to the List
action method. The .dialog()
method is called on the "NoteDialog" buttons
option defines 2 buttons and their click actions. The first is the "Save" button (the text in quotations is used as the text for the button) that will do an AJAX post to our Save
action method and send the serialized form data from the note form (targeted with the id
attribute "NoteForm"). Upon completion it will close the dialog widget and call the LoadList
to update the UX without a redirect. The "Cancel" button simply closes the dialog widget.
.live()
method handles binding a function to the "click" event on all elements with the CSS class named EditLink
. We use the .live()
method because it will catch and bind our function to elements even as the DOM changes. Since we will be constantly changing the note list as we add and edit we want to ensure that the edit links get wired up with click events. The function for the click event on the edit links gets the noteid
attribute and stores it in a local variable. Then it clears out the HTML in the dialog element (to ensure a fresh start), calls the .dialog()
method and sets the "title" option (this sets the title
attribute value), and then calls the .load()
AJAX method to hit our Edit
action method and inject the returned content into the "NoteDialog" .load()
method is complete it opens the dialog widget.
Create
action method. This binding is done via the .click()
method because it will only be bound on the initial load of the page. The add button will always exist.Content/Site.css
file to style our form and the add/edit links..ButtonLink { color:Blue; cursor:pointer; }
.ButtonLink:hover { text-decoration:underline; }
.Hidden { display:none; }
#NoteForm label { display:block; margin-bottom:6px; }
#NoteForm label > span { font-weight:bold; }
#NoteForm input[type=text] { width:350px; }
#NoteForm textarea { width:350px; height:80px; }
Discussion
Thanks for this type of blog. It helps me very much. Good post.
Justin Schwartzenberger
LEO
Good ,all right !!!
Hi Justin Schwartzenberger,
Thanks for post. I need your help. I need to validate my input. I can validate input in MVC 3. When i use jQuery UI then how i can validate my input. It will be very helpful for me if you give/post a sample application with validation.
Thanking You. Hasibul
Scott Xu
one suggestion: you can get the list from post back data which will save one round trip.
Justin Schwartzenberger
Justin Schwartzenberger
Justin Schwartzenberger
In testing out the above comment changes I noticed that the
Create
andEdit
methods needed to have theOutputCache
attributes applied to them as the calls to these via jQuery were getting cached in IE. I updated the article to include that info as well as theHomeController.cs
code which I apparently forgot to add! Good thing I put the zip file of the project up for download. Speaking of which, I updated the project to include these changes as well as the validation and one trip on save updates from the comments above.Hi Justin Schwartzenberger, Thanks for solution. I am able to validate my form. Can i use server side validation if I use jQuery form. If yes then how i can do that?
Nuri Yilmaz
Hello Justin!
Justin (!) time post! Thanks. I bet this page will be the most popular MVC3 blog page.
Tony Whalen
If you wrap your dialog container in a container div (e.g. ), you can then hook up your standard data annotation validators on DOM ready like this: $.validator.unobtrusive.parse($('#editContainer'));
you can then just call the valid() method on the form like this:
I also use the fantastic DataAnnotation Extentions
Tony Whalen
Sorry my e.g. didn't appear. It should have read
Justin Schwartzenberger
Thanks Tony Whalen and Justin Schwartzenberger,
Hi Justin Schwartzenberger,
I need another help.it will be very helpful for me(also others) if you create another blog post about saving master detail record with mvc3.
i am very new in ASP.net MVC. I can save master and detail record form view to controller when list item is fixed and input is taken from Html.TextBox.
Now i want to know how i can get value from label bcz I want to post a html table with label data.
There will be an Add button if I press it then it will add new row with data to html table. when i press submit button then it will post all table data.
I've checked following blog post Master Detail Form in asp.net Mvc 3 - I
Editing a variable length list
I am sorry for posting here. I know it is not forum site. I wrote you bcz i like your blog post. Hope you will help me.
Thanking You hasibul
Felix
I would like to elaborate on the topic of validation. In fact, my team pretty much gave up on JQuery dialog-based edit forms for anything but the most trivial situations or for some admin screens when validation need not be too user-friendly.
Our starting point: regular MVC Views, unobtrusive validation, and data annotation-based attributes. So, things like "Required", DataType() and Min / Max Length are enforced "out of the box". @Tony Whalen - try as I might, I was not able to successfully validate the form. Form.valid() always comes true. I will research further, since this would solve half of the situations. Did you see it work? Bonus question :) - does it populate ValidationMessage() / ValidationMessageFor() fields with error messages?
The other half of situations is when I need to validate some business logic on the server (item is in stock, booking is available, etc.). Again, with regular views showing an error is as simple as
ModelState.AddModelError("", errorMessage);
and validation will take care of everything (doncha love JQuery validation!). Here I would need to traverse ModelState Keys / Values, and - worse - populate validation messages for the form or for the field...Am I exaggerating the complexity? Is there a simpler way to wire validation from Model (DataAnnotations) through Controller (ModelState) to the form on JQuery dialog?
Thanks
Felix
Follow-up... I was able to get client-side validation working (and Validation Message is shown as well). Should be
I didn't have to wrap dialog in another container, either. So, I guess, if you don't have to have server-side (business rules) validation, dialog forms should work just fine.
Nuri Yilmaz
Hello Justin,
Will you update your code for data annotation validators?
Thanks.
Tony Whalen
@Felix - Glad you got basic validation working by calling the parse method and yes you're right, you don't have to add a container to make this work.
For more complex server-side validation, have you tried the new RemoteValidation capabilities in MVC3?
The other technique I've used is to return a JsonResult containing an Errors object being a list of ModelState errors along with a StatusCode of 500 (to cause the $.ajax to fail) and then handle them on the client. For example
The Errors property is an extension method as shown below:
Tony Whalen
then on the client
and to hook into the form's validation summary
}
Nuri Yilmaz
Tony: you talk about MVC3 RemoteValidation capabilities but you give samples code it beats me little bit.
When I modify Note class as shown for MVC3 RemoteValidation capabilities.
I could not get inform on error information on dialog form as "something wrong"
why should I use your advice instead of remote validation. anyway I could not work with it. Any idea?
Tony Whalen
@Nuri: I was referring to the new Remote DataAnnotations attribute as described
I wouldn't recommend use of the IValidatableObject interface
Felix
@Toni,
Yes, I am using RemoteValidation regularly (and love it). It works good with user deciding to initiate specific validation (obviously, the most common example is "is this userid still available" on registration page.
Here I am talking about really server-side business rules-based validation where the user submits a form, and server-side code may produce and error (like, You can't sign up for this class, or You can't complete this purchase, or similar).
The code that you posted for client-side is very similar to what I have (and it is similar to jquery.validate.js). I was just hoping that I could DRYly leverage out-of-the-box validation, rather than clone it.
Still, it's a big improvement over what I thought is possible. And by the way, I think we (I) took this conversation into somewhat off-topic direction. But since Justin hasn't reprimanded me yet - I assume that he is OK :))
Justin Schwartzenberger
I am stoked that you guys are all contributing! My goal of this blog is to provide help to other developers out there and your contributions are aiding in that mission. Please always feel free to take the discussion wherever you need to in order to work through things and discover supportive solutions. :)
Justin Schwartzenberger
Felix
FWIW, I don't like returning 500. In our system, 500 codes are used for system generated errors. We often link them to monitoring and notification tools. To mix business errors in makes it much more complicated for operation folks. Instead, since controller returns
Json(new { Success = noteId > 0 });
I would do something like this on the client:Obviously, technically both approaches are possible; and equally obvious that I like my better :)
Tony Whalen
@Felix: I think I also prefer your approach. Thanks for the input and don't give up on the jQueryUI dialog for building these types of client-side apps!!
Nuri Yilmaz
hi felix, and tonny, Im feel myself newbie on Jquery. could you please define rwaiaUI? thanks
William Bowsher
Fantastic article helped me loads creating a complex set of editors for 3 inter linked objects.
Keep up the good work.
Justin Schwartzenberger
stillhateMVC
Doesn't seem to matter who or where I get examples of JQuery, they never work.
This project does not work and I am using VS 2011 MVC 3 I have installed the latest and then tried again with your version of JQuery but no go.
I give up on JQuery.....
Justin Schwartzenberger
Hi Justin, Thank you for your post. Very clearly and helpful sample and a good documentation. It's just I'm looking for my current project. I'll try to use it in next week. Thanks, Jimmy
Arturo Chamorro
Very good your blog, congratulations. I made some improvements to make the window modal validation on the client side and server-side later. I can send you the code to post to this blog, since I've seen that many have this problem, searching here and there, I managed to fix the scripts jquery.unobtrusive-ajax.min.js for validation in the modal window. Show me where I can please send the source.
Justin Schwartzenberger
Derek
Hey there. I am in a little bit of a dilema. I am attempting to put an entire .ascx file into a modal window, with jquery validation and Datepickers and on and on. I was doing this with the simpleDialog (I am using MVC2 by the way and not 3) jquery library. But I am confused about how to do this with the jqUI dialog library... How would I open an Html.Action() inside the dialog window?
Confused???
Justin Schwartzenberger
kesar
This is the most useful article I've ever read, in my 6 years as a .NET developer.
Completely changed the way I use MVC and jQuery.
It has made development so enjoyable.
Great article!!
Cheers
Justin Schwartzenberger
kesar
Very glad to hear that and stoked that I could help!
Fernando
Hello, first of all thanks for the information.
I have a problem, in my development environment all works fine, but when I publish the website in IIS jQueryUi forms are empty. You know why?
Thanks and best regards.
https://dl.dropbox.com/u/2264720/ErrorjQueryUI_ISS.png
Fernando
I have found that IIS jQueryUI Demos work.
![alt text][1]
[1]: https://dl.dropbox.com/u/2264720/jQueryUIDemo.png JQueryUIDemoIIS
Find how to display Jquery dialog when using AJax in asp.net MVC here http://www.vishalpatwardhan.com/2011/09/display-jquery-dialog-when-ajax-calls.html
Avi
thanks..
XOS
I'm calling an action that returns an excel file as a response stream. The action is called but the file isn't returned.
How can I configure the button on the dialog to do this?
TommyRojo
Awesome post man. Jquery UI + MVC = Pure awesomeness!
thulasi ram
$.post("/Home/Save", $("#NoteForm").serialize(), function () { $("#NoteDialog").dialog("close"); LoadList(); });
this is ok but, i need with multiple file uploading...
Ted M
Thank you... this is great!!!
Bryan
Great post.
I'm building something similar and have been referencing this and noticed than when hitting enter in the modal, that the dialog will submit and the browser will end up at http://localhost:50410/Home/Save with the partial view rendered. (Note that you have to fill in values in both fields and then hit enter with focus in the Title field because the Body is multiline)
If you click Save, then you get the intended functionality where the partial view is swapped into the page.
I saw this in my test and in the downloaded sample. It occurred with both IE9 and Firefox. It seems like we need to disable the default form submit. I'm looking into that but wanted to see if you had thoughts.
Bryan
To better understand what I meant above, copy the HomeController.Save action and paste a copy called SaveFromForm. Then change the NoteForm view to target this action:
You'll see that if you hit enter, the SaveFromForm is hit. If you click the button, Save is called.
One thing I've tried that can be done is to hook the submit event and prevent the default behavior and then have it call our save behavior, which I've moved into its own defined function. Here's the script on the Index now:
Mohammad
This is great. thank you very much.
Jason Wood
This is exactly what I was looking to accomplish. Great help thanks!
ElvaScharf94
Dude that is one of the coolest things ive read in a long time.
Sandra
Hello there. First thanks and compliments for the post,it's great and it took me throw creating new instance of my db,the create part was successful and great,but the thing is that my edit dialog shows up but it's empty and i have checked it couple of times but it seems like everything is alright,like in the example. Justin or someone else do you maybe have idea why is that,and can you help me please. I'm beginner and you all know how is that,right :)
And one more thing. I'd like to combine this with Knockout,actually I'd like the listing to be with Knockout so later on my n:n relation of the model to be realized much more easily,can I do that?anyone?
Thanks so much at advance I'd really appreciate your time
No new comments are allowed on this post.