ASP MVC3 – Editing records with jQueryUI Dialogs and AjaxForms

In this screen cast I will show you a demo of how to use  jQueryUI dialogs and MVC AjaxForms to create a rich and simple experience for users when editing records.

The technique is simple; you dynamically load a partial view into the DIV dialog  . There are a few tricks to wire up the validation, and to identify success over failure. .

Get the source code by clicking here, take a look and let me know what you think.

Update: 

After many requests, I’ve created a Razor version, all interested can read the post here. 

About these ads

About ricardocovo

Senior Software Architect/Developer with extensive experience in web related technologies.

73 Responses to “ASP MVC3 – Editing records with jQueryUI Dialogs and AjaxForms”

  1. Hey Ricardo,

    This is great. I hope to walk through your code to learn more.

    Ken

  2. great post..it is working when i implemented your instructions step by step..
    but i dont do it for create operations..i guess there some missing jquery libraries for create.

    How can I achieve create operations like edit?

    Appreciate..

    • Hi Alex,

      The jquery libs for create/update would be the same. Basically, the concept would be the same: you create the partial views for your create action, make sure you use an ajax form and that all the wiring is done (OnSuccess function exist, UpdateTargetId points to the appropriate Div).

      Are you having any particular problem?

      • Hi Ricordo,

        The link to ASPX version download is not working.Could you give me the demo in MVC 4 ,or anything that is available.

      • Nishanth,

        I have corrected the link. Sorry about that.

        -Ricardo

  3. I missed some points..thank you for your help ricardo..

    best wishes..

    • Hi Ricardo, great post, the links to the code and the demo aren’t working for this or the razor aren’t working anymore. any chance of you fixing this?
      thanks in advance, Steve

      • Steve, the code has been reposted. Please try the link again.

        Thanks for letting me know about the issue.

  4. Hi Ricardo,

    First of all, your post is so nice and useful. I dunno all the steps of your work to my project and I have done create,edit and delete operations now.

    I am using MVC 2 in my project and mvc client-side validations doesn’t work in my project after adding the libraries below :

    “~/Scripts/jquery-ui.min.js”
    “~/Scripts/jquery.unobtrusive-ajax.js”
    “~/Scripts/jquery.validate.min.js”
    “~/Scripts/jquery.validate.unobtrusive.min.js”

    Before adding these libraries, my MVC client-side validations works with these libraries :

    “/Scripts/Using/jquery-1.4.4.js”
    “/Scripts/Using/jquery.validate.js”
    “/Scripts/Using/MicrosoftMvcJQueryValidation.js”

    and by adding the line EnableClientSideValidation() function.

    What is the missing point here?
    How can I achieve mvc 2 client-side validations?

    Thanks for your help..

    • Hello, thanks for the feedback.

      Unobstrusive validation is a feature of MVC3. I imagine your issue is re-binding the client-side events after you load the partial view into the div. There must be a way with regular validation, but I do no have the info on-hand. I’m a bit busy but if I get some time I’ll investigate on it.

  5. Thanks for your help Ricardo..

    Thanks in advance..

  6. Ricardo,
    Thanks for the great video. However after you make updates to anyone of your items (either Name or Description) and want to make another update immidiately after the first one, you will get the very first text. It seems like your GET method does not trigger each time, it triggers only once. But POST works fine. What do you have to do to get new data each time you click on Edit button?
    Look forward to your answer.
    Thanks,
    Tony

    • Tony,
      I was not able to reproduce the behaviour you are describing. I can edit all the items on the list one after the other, or in any order and I will always get the right edit dialog.
      The GET should trigger every single time. If you check the $(".editLink").click...function, you will notice I am getting the partial view that is actually on the HREF of the link. So it will always load the right information.
      If you send me steps to reproduce I could see try to reproduce it again.
      Thanks for the nice comments,

      • Once you edit and update a record, try to edit the same record again you will get the original data in the dialog fields not the recently updated data.

      • Tony, I tried it again and I cannot reproduce it this issue.

        However, please be note that this sample does not persist data, as that was not the intent of the exercise. The car list is in memory and will be reloaded every time the application is re-started.

      • Tony,

        Just so you know, I’m getting the same issue. That said, I also agree with Ricardo that it (should) get the data every time… I’m trying to figure this out and see what is going on – it must be something to do with caching

        Allan

    • [HttpGet]
      [OutputCache(Duration = 0)]

      This should get the new data every time you click on edit.

  7. Hi Ricardo,

    Is there a way for this mini-project working in MVC2 with its all functionalities?

    • Semir,

      Unobstrusive validation is a feature of MVC3, so the problem would be to re-bind the validations, if you can figure out that part, the rest should work.

  8. Hey! Excellent walk through! I would like to know how would you handle dialog concurrency in a scenario like this. I mean, what if I open two dialogs? I was thinking in implementing some kind of form namespace, which seems very complex. Any thoughts on such approach?

    Thanks!

    • THe dialogs are opened on a modal form, so I don’t think you can open twice.

      If you decide not to go modal to allow multiple dialogs, you would probably have to create on the fly the dialog div and the update div. Then, the dialogs will not conflict with each other because each one will have their own form.

      Hope this helps,

  9. I followed your example and modified my existing code to match. The dialogs display and go away just fine, and everything posts — *except* that none of my javascript enabled functionality works on the dialogs now (validation, calendar popup, etc).

    Also I noticed something strange — I can create a situation where I post form values to an action, and when I check ModelState it claims it is valid, but then if I do a ModelUpdate, it indicates that the modelstate is in fact NOT valid. Any thoughts?

    • Hi Stacy, what version of MVC are you using? Please notice that uses unobstrusive validation which is available on MVC3. Make sure the parent page is including all the required javascript libraries, including these 3: jquery.unobtrusive-ajax.js, jquery.validate.min.js & jquery.validate.unobtrusive.min.js.

      Also, make sure unobstrusive validation is enabled, it is usually on your web.config like this:

      But you can also do it at the page level, like this:

      I hope this helps,
      -Ricardo

  10. Excellent work, I’m trying to handle these scenario in razor view, but I’m bit confused. Anyone have done this in razor view ? Is there anything here that cannot be used in razor ? Renamed all view files and layout to .cshtml and ofcourse and updated all syntax to match razor view but without luck.

    Regards,

    • I don’t see why it wouldn’t work with Razor. Where is it failing? What are you experiencing?

  11. thank you for quick answer.
    link is open on classic way, it sends me to another page, no popup.
    Checked path to scripts, layout, can’t figure.

  12. sorry for distraction. My bad. Works perfectly, can belive what I’m missing :) Big shame to share. Once again great work.

  13. Marcus Mattingly Reply July 14, 2011 at 4:06 am

    Wow, thanks for posting this. This is exactly what I needed. However…

    Anyone have any issues when you have a DropDownList on the modal dialog?

    When I submit the update I get an error about the field being an int but it needs to be a SelectListItem. Something like that.

    Any help appreciated.

    Thanks!

    • Since you are mentioning DropDownList and SelectListItem, I am assuming you are using this with Web Forms, correct?

      I am not sure this method will work with web forms straight away. Some testing/modifications will be required. Can you give more details on what you are trying to do?

      • Marcus Mattingly July 14, 2011 at 10:11 am

        Actually I am using the Html.DropDownListFor, but it seems to be working now. It must have been one issue causing another. I really appreciate the reply anyway.

  14. When I click the update button on the edit partialview, the information is updating with success and returning True, but the Index form is showing the update-message label instead of updating the information. I’m using MVC2. Is this where it would fail because this is for MVC3?

    • The fact that you are getting the message on the “update-message” div implies that everything has worked (I assume it contains ‘True’). Maybe there is something within the ‘if’ statement that is breaking? Have you debugged the Javascript?

  15. why do my cancel button doesn’t work?
    and when i click it i can’t update my item from the database anymore.

  16. Clicking edit brings up the edit form and I am able to make the changes and save successfully. The issue is that when I click update, though it does successfully do this, it redirects me to the action URL ‘/Testimonial/Edit/5/’ and the only content on that page is ‘True’.

    To ensure that the link doesn’t preform the correct action I have put in there ‘e.preventDefault()’ and ‘return false’ both of which should stop it from doing the normal action of a link.

    Any ideas why I would still be redirected to the Edit page containing the text ‘True’ opposed to it updating the update-message content et cetera?

  17. Its work fine on FF,Chrome,Safari. but it raise problem in IE. it can’t call the action.

    • I’m not sure what your problem might be… does the solution found by shaneje (look up in the thread) help you?

  18. It is not MVC3 bro! :(

    • Yes. It is. At least when I open my project, the System.Web.Mvc (under references), I can see is version 3.0.0.

      In any case, the question is, did you find this useful?

  19. Hi Ricardo,

    First of all thank you for this excellent example of using JQuery and Ajax in MVC application.

    I’m trying to use it out in MVC3 application with Razor and all works fine except main part – when I click “Edit” button nothing happens. I’ve checked what all people wrote here but it’s still not working. What to do?

    Thank you in advance.

    Goran

  20. Hi again Ricardo,

    Actually, I forgot to add Edit view for Cars controller. All works fine with MVC3 and Razor now.

    Thank you very much once again.

    Regards,

    Goran

  21. Great work man. Exactly what I was looking for. Keep it comming….

  22. Congratulation Ricardo. …great work !!!!
    I just change my Site.css file and then I can anymore back to the original style.
    what can I do ????

    thanks

    Rodrigo

  23. Hi Ricardo,
    Thanks for your blog. I was able to have the popup for edit for my application. However, if there is a server side error( my applictaion have some server side validations), then I am not able to get the message “Please review your form”. Can you please guide in showing that message

    • Anphy,

      I am working on a new post that will cover this scenario. I am a bit busy though, so it might be a week or so.

      You could do a few of things, here are some ideas:
      – Do the validation before you submit the form with an AJAX call.
      – Return a string and look for it indicating that there was an error (ugly, but it works).

      I have used a standard json object that contains a status and an object… Maybe I’ll do a post about that too ;)

  24. Hi Ricardo,

    Very nice article, can’t seem to to make it work with Razor Framework, If it not a hassle , Can you give a sample of this in MVC3 Razor ? It would be greatly appreciated

  25. Thanks for the excellent tutorial, I really wanted something that could teach me about the underpinnings of the ajax model. I started using Razor engine and found that I had limitations so I wanted to revert back to .aspx and have the use of Master Pages. This tutorial did just that! If you could do a tutorial on FileUpload that would be great!

  26. @Brian, @paja, @Goran Tesic, @Bob Nicolas

    I finally took the time to do a Razor version. You can check it out here: http://wp.me/p7vU7-3l.

    I introduced a few improvements as well.

    Hope this helps,

  27. Hello Sir!
    I am trying to do something similar on ASP.NET MVC3 C#, but i see, the moment i open the edit form in dialog, i can’t able to do update.I saw the first time its works fine, but then when next time i hit update button, i see its appends to new sets of data to old on post url.I saw the Post details in Firebug , Please let me know how can i fix it?

    I will appreciate your help.

    Thanks,
    Kumar

  28. I’m sorry if i didn’t get it by reading the comments and the answer is somewhere there,but i have the same issue as someone else that posted above in the comments :link is open on classic way, it sends me to another page, no popup.Checked path to scripts, layout, can’t figure.
    Ricardo can you please give me some direction what the problem may be.

    Thanks. I’d really appreciate it. I’m beginner and I’m kind of stuck here. :) But your example is great just I want to make it work :D

    • Hi,

      When the links opens normally, it means that the click event was not correctly binded. If you are positive all the jquery references are there, then check that there are no other javascripts errors on the page.

      Did you start from the example source code?

      Hope this helps,
      -Ricardo

  29. Hi Ricardo,
    Excellent post. I have implemented the MVC3 solution and also added the Create and Delete dialog and methods based on your Edit. I have a different way of handling the grid because I am reloading it after every successful CRUD method and it is a partial view as well.
    But I have noticed something strange in the update-message behavior when it returns data.Success = false. I have debugged it and the data is there and the error message is there as well and the code goes in the else part of the function updateSuccess(data) but the text doesn’t show. And it does not happen if this unsuccessful result is the first action after refresh. It only happens after at least one successful action (dialog open, save, returns data.Success true).
    Is there a problem with cashing? I suspect something along that line but have no idea how to solve it. Please help if you can. Thank you.

  30. First of All I thank you

    My question is : How to change the initial position of the dialog. I mean; when I click on Edit button I want the dialog to be displayed in right side of the screen instead on the center of the screen .. is it possible if yes how ?
    thanks in advance

  31. Hi,

    Thanks for this wonderful article. I am new to Asp.Net MVC. I am trying to upload file using modal popup. This article I have tried out to upload a file . But as i submit the file is not uploaded on the controller. Where as I have tried without the popup , the file upload controller doesn’t receive the file path on the server. How do I make it submit the file upload.

  32. hi Ricardo

    i want to edit record inplace so how can i do this using ajax mvc .please post some code to do it .it would be very helpful

  33. Thanks for putting this together.

  34. Great post Rocardo, i have learnt alot. thank you for your series of tutorials.

  35. Hi, Thank you for sharing your knowledge. As a beginner, I’d say this is so far what I found the most clearly described and easy to follow MVC modal popup sample. I downloaded yours and transformed it to MVC 5. It works fine except the twitter style complete message not shown. Can you give me some tips to debug it? Besides, just wanted to clarify a couple things, (1) in the updateSuccess function, why do you need to find “tr”, “carName” etc.? Is it because you don’t use a database in the sample but you want to show the effect that the record has been update?

    • The main reason for having to find the “tr” and update the information is to keep the table information updated after you have submitted your change on the modal window, without having to reload it.

      As per your issue with the twitter type message, do you get an error? there are many other/newer libraries/functions for messaging out there, which you can choose to use.

      • Thank you so much for prompt reply. Yes, I used NuGet to get everything update. After I clicked Update (in the popup), it does to another page which showed “{“Success”:true,”Object”:{“Id”:1,”ImageFileName”:”FordFocusElectric.jpg”,”Name”:”Ford Focus Electricaaa”,”Description”:”Great looking car… plus is green.”}}” and the url is http://localhost:1773/cars/Edit/1?Length=4.
        I used F12 developer in Firefox to browse (not sure this is right place to check) and found the following two errors:
        “The connection to ws://localhost:3406/dkflfjdl……… was interupted while the page is loading”
        “no element found”

      • Jim, the fact that you are getting this “Length=4″ on the URL is leading me to believe there was a problem with the migration to the new version of MVC and the URL is not being generated correctly.

        Other that that, is tough to determine the error by the info given.

        Keep in mind this sample is a few years old, even jquery might have changed substantially.

      • I know…and that’s why I tried to transform it to MVC5. However, as I said, this is the easiest understandable I found so far (for beginner, of course it also depends on individual’s technical background). Anyway I have figured out quite a few tricks from your sample already. Unfortunately I just cannot do it the best. Once again, thanks for sharing with us.

  36. Hello Ricardo,

    I tried to debug to see why the twitter style message is not coming up. I found that the execution ends at the line “return Json(JsonResponseFactory.SuccessResponse(car),JsonRequestBehavior.DenyGet);” whereas your version continues to function updateSuccess(data) {..}. I tried my best the compare the code and didn’t see any difference. By any chance, will you have a clue what the problem would be. Thanks.

  37. Hello Ricardo,
    I am running into some issues trying to replicate your demo application. I am redoing your demo using ASP.NET MVC 4 Razor (VS2012) with some different data (example, updating a list of users). When trying to update a dialog windows opens, I make the changes I want and when clicking on update the index form does not reflect the new changes I have to refresh the whole index page (F5) to see the new changes but in the data base all changes had been taken successfully.

    What could I been doing wrong?

Trackbacks/Pingbacks

  1. How to reload dropdown list values in asp.net mvc3 without refreshing page - November 18, 2011

    […] make things easier on the user, I have implemented a modal dialog using jQuery which allows the user to add an option to the db without having to leave the form to […]

  2. ASP MVC3 – Editing records with jQueryUI Dialogs and AjaxForms – Razor Version | Ricardo Covo's Weblog - April 6, 2012

    […] I’ve gotten to provide a Razor version of a sample solution I provided a few months ago on Editing records with jQueryUI Dialogs and AjaxForms, which was originally posted using aspx views. If you haven’t read it or seen the video, […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 215 other followers

%d bloggers like this: