Build a dialog form to handle inline data edits using the jQuery UI library in a MVC 3 application

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

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

    tag with the 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
    tag with 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
    tag is given a CSS class named "Hidden" that will set the 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
    element rendered in their browser as the page renders and then it will hide after that jQuery call. Adding the display:hidden to the
    element via CSS will ensure that it is never rendered until the user triggers the request to open the dialog.

    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 LoadList that handles the AJAX call to the List action method. The .dialog() method is called on the "NoteDialog"

    element and the options are set for the dialog widget. The 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.

    The .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"

    element. Once the .load() method is complete it opens the dialog widget.

    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 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.

    Finally, we toss in some CSS in the 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; }
    

    With all of our code in place we can do an F5 and see our list of notes:

    Note list

    If we click on an edit link we will get the dialog widget with the correct note data loaded:

    Edit note

    And if we click on the add new note link we will get the dialog widget with the empty form:

    New note

    The end result of our solution tree for our sample:

    Solution Tree

    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!

    Discussion

    Hasibul
    10 Jun, 2011 02:33 PM

    Thanks for this type of blog. It helps me very much. Good post.

    10 Jun, 2011 02:50 PM

    Hasibul
    Welcome. Glad to be of help!

    LEO
    LEO
    12 Jun, 2011 09:31 AM

    Good ,all right !!!

    Hasibul
    12 Jun, 2011 10:13 AM

    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

    12 Jun, 2011 04:34 PM

    one suggestion: you can get the list from post back data which will save one round trip.

    $.post("/Home/Save",
    $("#NoteForm").serialize(),
    function (data) {
        $("#NoteDialog").dialog("close");
        $("#ListDataBlock").html(data);
    });
    
    12 Jun, 2011 10:45 PM

    Hasibul
    You can use the jQuery Validation library to handle validation on the client side fairly easy. Check the Scripts dir in the MVC 3 project to see if the jquery.validate.min.js file is in there. If not, you can use NuGet to fine the jQuery Validation package and get it installed that way. From there, add a reference to the script file in the _Layout.cshtml file:

    
    

    Then add some script code to the /Views/Home/NoteForm.cshtml file to configure the form for validation:

    
    

    This example makes both the Title and Body required. The last piece to do is to add some jQuery code to the $("#NoteDialog").dialog() button settings for the "Save" button in /Views/Home/Index.cshtml.

    "Save": function () {
        if ($("#NoteForm").validate().form()) {
            $.post("/Home/Save",
                $("#NoteForm").serialize(),
                function () {
                    $("#NoteDialog").dialog("close");
                    LoadList();
                });
        }
    }
    

    You can wrap the $.post() call in an if statement that calls the .validate().form() method on the "NoteForm" element. This will use the jQuery Validation library to check the form data client side based on the settings and return a true if valid or a false if not. If it is false the form elements will automatically get updated with some feedback text as to what the errors were and the dialog widget will remain open.

    12 Jun, 2011 10:54 PM

    Scott Xu
    Great suggestion! If we update the Save method in the HomeController class to make the call to the GetAll method on the manager and then return the "List" partial view, we can use that to update the "NoteListBlock" element and eliminate the second trip. The update to the Save method:

    [HttpPost]
    public ActionResult Save(Note note)
    {
        var manager = new NoteManager();
        manager.Save(note);
        var model = manager.GetAll();
        return PartialView("List", model);
    }
    

    And the $.post() call actually needs to target the "NoteListBlock" element:

    $.post("/Home/Save",
        $("#NoteForm").serialize(),
        function (data) {
            $("#NoteDialog").dialog("close");
            $("#NoteListBlock").html(data);
        });
    

    With those changes in place the "Save" button makes a single trip and uses the return data to "reload" the list content.

    12 Jun, 2011 11:11 PM

    In testing out the above comment changes I noticed that the Create and Edit methods needed to have the OutputCache 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 the HomeController.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.

    Hasibul
    13 Jun, 2011 05:01 AM

    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
    Nuri Yilmaz
    16 Jun, 2011 12:18 PM

    Hello Justin!

    Justin (!) time post! Thanks. I bet this page will be the most popular MVC3 blog page.

    Tony Whalen
    Tony Whalen
    16 Jun, 2011 01:14 PM

    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:

    $('#editForm').submit(function (e) {
        var frm = $(this);
        if (frm.valid()) {
    

    I also use the fantastic DataAnnotation Extentions

    Tony Whalen
    Tony Whalen
    16 Jun, 2011 01:21 PM

    Sorry my e.g. didn't appear. It should have read

    16 Jun, 2011 03:44 PM

    Tony Whalen
    Thanks for the example! Hasibul can use that to craft validation logic server side and wire it up client side. Nice little bonus that the DataAnnotation Extensions library is available via NuGet too!

    Hasibul
    19 Jun, 2011 06:35 AM

    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
    Felix
    20 Jun, 2011 03:32 AM

    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
    Felix
    20 Jun, 2011 05:06 AM

    Follow-up... I was able to get client-side validation working (and Validation Message is shown as well). Should be

    $.validator.unobtrusive.parse("#NoteForm");
    var frm = $("#NoteForm");
    if (frm.valid()) {
        $.post(...)
    }
    

    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
    Nuri Yilmaz
    20 Jun, 2011 10:25 AM

    Hello Justin,

    Will you update your code for data annotation validators?

    Thanks.

    Tony Whalen
    Tony Whalen
    20 Jun, 2011 12:30 PM

    @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

                if (!ModelState.IsValid)
            {
                // Invalid - redisplay form with errors
                this.Response.StatusCode = 500;
                return Json(new { Errors = ModelState.Errors() });
            }
    

    The Errors property is an extension method as shown below:

            public static IEnumerable Errors(this ModelStateDictionary modelState)
        {
            if (!modelState.IsValid)
            {
                return modelState.ToDictionary(kvp => kvp.Key, 
                    kvp => kvp.Value.Errors.Select(e => e.ErrorMessage)
                        .ToArray()).Where(m => m.Value.Count() > 0);
            } 
            return null;
        }
    
    Tony Whalen
    Tony Whalen
    20 Jun, 2011 12:31 PM

    then on the client

                if (frm.valid()) {
                $.ajax({
                    url: frm.attr("action"),
                    type: 'POST',
                    data: frm.serialize(),
                    success: function (response) {
                        killEditDialog();
                    },
                    error: function (result) {
                        var ui = new rwaiaUI();
                        ui.showFormErrors(frm, result.responseText);
                    }
                });
            }
    

    and to hook into the form's validation summary

        rwaiaUI.prototype.showFormErrors = function (frm, errorText) {
    
    var errorObj = JSON.parse(errorText);
    var errors = errorObj.Errors;
    
    var container = frm.find("[data-valmsg-summary=true]"),
            list = container.find("ul");
    
    if (list && list.length && errors.length) {
        list.empty();
        container.addClass("validation-summary-errors").removeClass("validation-summary-valid");
    
        $.each(errors, function () {
            $("
  • ").html(this.Value[0]).appendTo(list); }); }
  • }

    Nuri Yilmaz
    Nuri Yilmaz
    20 Jun, 2011 02:26 PM

    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.

    public class Note : IValidatableObject
    {
        public int Id { get; set; }
    
        [Required]
        public string Title { get; set; }
    
        [Required]
        public string Body { get; set; }
    
        public IEnumerable Validate(ValidationContext validationContext)
        {
            yield return new ValidationResult("something wrong!");
        }
    }
    

    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
    Tony Whalen
    20 Jun, 2011 02:39 PM

    @Nuri: I was referring to the new Remote DataAnnotations attribute as described

    I wouldn't recommend use of the IValidatableObject interface

    Felix
    Felix
    20 Jun, 2011 06:55 PM

    @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 :))

    20 Jun, 2011 07:18 PM

    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. :)

    20 Jun, 2011 09:26 PM

    Tony Whalen
    I really like your approach of returning the 500 status code and wiring up the error handler on the client side. That is slick.

    Felix
    Felix
    21 Jun, 2011 12:39 AM

    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:

    function(data) {
       if (data.Success) {
           killEditDialog();
        } else {
           var ui = new rwaiaUI();
           ui.showFormErrors(frm, data.ErrorMessages);
        }
    }
    

    Obviously, technically both approaches are possible; and equally obvious that I like my better :)

    Tony Whalen
    Tony Whalen
    21 Jun, 2011 07:56 AM

    @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
    Nuri Yilmaz
    29 Jun, 2011 11:49 PM

    hi felix, and tonny, Im feel myself newbie on Jquery. could you please define rwaiaUI? thanks

    William Bowsher
    William Bowsher
    08 Jul, 2011 09:12 AM

    Fantastic article helped me loads creating a complex set of editors for 3 inter linked objects.

    Keep up the good work.

    08 Jul, 2011 02:47 PM

    William Bowsher
    Thanks for the feedback. I'm glad it was of help!

    stillhateMVC
    stillhateMVC
    19 Jul, 2011 08:54 PM

    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.....

    19 Jul, 2011 09:54 PM

    stillhateMVC
    Doh, that sucks! Maybe we can help get things working for you if you haven't given up 100%. If you want to give it another shot, let me know what specifically doesn't seem to work for you (if you can) and also what user agent (browser) you are using. We can see if we can work this stuff out for you and maybe get your handle changed from "stillhateMVC" to "slowlystartingtocomearoundonMVC" :)

    Jimmy
    12 Aug, 2011 05:26 AM

    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
    Arturo Chamorro
    12 Aug, 2011 08:49 AM

    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.

    12 Aug, 2011 04:14 PM

    Jimmy
    Welcome!

    Arturo Chamorro
    Thanks for the feedback! If the code is short you can just put it in a new comment (or two). Otherwise you could host it somewhere and put a link to it from a new comment.

    Derek
    Derek
    18 Aug, 2011 03:41 PM

    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???

    18 Aug, 2011 06:03 PM

    Derek
    Are you referring to having a dialog open, then clicking on a link in the dialog and having the contents of the dialog change based on the link navigated to?

    kesar
    kesar
    31 Aug, 2011 08:42 AM

    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

    31 Aug, 2011 02:35 PM

    kesar
    Very glad to hear that and stoked that I could help!

    Fernando
    Fernando
    02 Sep, 2011 07:46 AM

    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
    Fernando
    02 Sep, 2011 08:03 AM

    I have found that IIS jQueryUI Demos work.

    ![alt text][1]

    [1]: https://dl.dropbox.com/u/2264720/jQueryUIDemo.png JQueryUIDemoIIS

    vishal patwardhan
    15 Sep, 2011 05:13 PM

    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
    Avi
    05 Oct, 2011 06:00 AM

    thanks..

    XOS
    XOS
    25 Nov, 2011 09:12 AM

    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?

    buttons: {
                        Export: function () {
                            $.post("/Search/ExportToExcel",
                            function () {
                                $("#export-excel").dialog("close");
                            });
                        }
    
    TommyRojo
    TommyRojo
    20 Dec, 2011 05:25 AM

    Awesome post man. Jquery UI + MVC = Pure awesomeness!

    thulasi ram
    thulasi ram
    17 Jan, 2012 10:43 AM

    $.post("/Home/Save", $("#NoteForm").serialize(), function () { $("#NoteDialog").dialog("close"); LoadList(); });

    this is ok but, i need with multiple file uploading...

    Ted M
    Ted M
    26 Jan, 2012 10:22 PM

    Thank you... this is great!!!

    Bryan
    Bryan
    30 Jan, 2012 06:16 PM

    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.

    30 Jan, 2012 07:52 PM

    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:

    Html.BeginForm("SaveFromForm",...
    

    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:

    $(function () {
        $("#NoteDialog").dialog({
            autoOpen: false, width: 400, height: 330, modal: true,
            buttons: {
                "Save": function () { saveNote(); },
                Cancel: function () { $(this).dialog("close"); }
            }
        });
        $(".EditLink").live("click", function () {
            var id = $(this).attr("noteid");
            $("#NoteDialog").html("")
                .dialog("option", "title", "Edit Note")
                .load("/Home/Edit/" + id, function () { $("#NoteForm").submit(function (e) { e.preventDefault(); saveNote(); }); $("#NoteDialog").dialog("open"); });
        });
        $(".AddLink").click(function () {
            $("#NoteDialog").html("")
                .dialog("option", "title", "Add Note")
                .load("/Home/Create", function () { $("#NoteForm").submit(function (e) { e.preventDefault(); saveNote();ov }); $("#NoteDialog").dialog("open"); });
        });
        LoadList();
    });
    function LoadList() {
        $("#NoteListBlock").load("/Home/List");
    }
    
    function saveNote() {
        if ($("#NoteForm").validate().form()) {
            $.post("/Home/Save",
                $("#NoteForm").serialize(),
                function (data) {
                    $("#NoteDialog").dialog("close");
                    $("#NoteListBlock").html(data);
                });
        }
    }
    
    Mohammad
    Mohammad
    01 Mar, 2012 04:10 AM

    This is great. thank you very much.

    22 Mar, 2012 04:51 AM

    This is exactly what I was looking to accomplish. Great help thanks!

    ElvaScharf94
    ElvaScharf94
    28 Mar, 2012 02:53 AM

    Dude that is one of the coolest things ive read in a long time.

    Sandra
    Sandra
    12 Apr, 2012 02:33 PM

    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.