ASP MVC3 – Editing records with jQueryUI Dialogs and AjaxForms – Razor Version

This post is in response to the several requests 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, please take a look at it first; as most of the concepts will remain the same. .

So this solution is practically unchanged compared to the original, however I did I introduced 2 improvements (which could also apply to the aspx version).

  1. I realized after I did my original post that I was able to get data on the handler function from the ajax form; so I am no longer looking into the response div for my data (which was kind of a hack). Instead I am now using it properly by receiving the data directly.
  2. I use a JsonStandardResponse, which I have been using in my projects succesfully and make things a bit easier. (See my previous post: Json Standard Responses for your Ajax Calls). So the controller action was changed to return JsonResult instead of a regular ActionResult with Content.
Here are the details of the change in the controller:
[HttpPost]
public JsonResult Edit(CarModel model) {
if (ModelState.IsValid)
{
CarModel car = CarRepository.GetCars().Where(c => c.Id == model.Id).FirstOrDefault();
car.Name = model.Name;
car.Description = model.Description;
return Json(JsonResponseFactory.SuccessResponse(car),JsonRequestBehavior.DenyGet);
}
else {
return Json(JsonResponseFactory.ErrorResponse("Please review your form"), 
            JsonRequestBehavior.DenyGet);
}
}


Notice that if the ModelState is valid I proceed with the change , and regurn a SuccessResponse, which includes the object car (this will get added to the standard json response).

return Json(JsonResponseFactory.SuccessResponse(car),JsonRequestBehavior.DenyGet);

If the state is not valid, we will return a ErrorResponse:

return Json(JsonResponseFactory.ErrorResponse("Please review your form"),
            JsonRequestBehavior.DenyGet);

With the Controller ready,  the UpdateSucces function (which is specified as the OnSuccess handler for the Ajax Form) is now as follow:

function updateSuccess(data) {
 if (data.Success == true) {
 //we update the table's info
 var parent = linkObj.closest("tr");
 parent.find(".carName").html(data.Object.Name);
 parent.find(".carDescription").html(data.Object.Description);
 //now we can close the dialog
 $('#updateDialog').dialog('close');
 //twitter type notification
 $('#commonMessage').html("Update Complete");
 $('#commonMessage').delay(400).slideDown(400).delay(3000).slideUp(400);
 }
 else {
 $("#update-message").html(data.ErrorMessage);
 $("#update-message").show();
 }
}

This, compared to the original implementation is much cleaner, because we get the data in json form directly in the function, and thanks to the JsonStandardResponse, I also get a copy of the updated object.

That is it. Those are the only two updates.

Download the Source Code.

Hope this helps!

Author: ricardocovo

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

67 thoughts on “ASP MVC3 – Editing records with jQueryUI Dialogs and AjaxForms – Razor Version”

  1. Thank you! This was just what I needed and I was able to get it working very fast! Although I can’t get the validation to bind yet…still working on that.

  2. This is the best example I have seen showing the use of using jQuery and Ajax for editing. Is there any chance of showing your example handling Insert and Delete too so we have a full CRUD example?

      1. Hi Ricardo,
        Many thanks for the quick response. I didn’t realise you had a Delete example, that’s great! You coding style and the way you describe things is excellent which is why I was hoping you covered insert and delete too. I’ll take a look at your approach to deleting and hopefully by mixing some of your edit and delete ideas together I should be able to create some code for inserting too.

        Cheers
        Mitch

      2. Would it be possible to provide those tweaks, I’m new to using JSon and a step in the right direction would be great if you do end up having the time. After Panama that is!

  3. Hello Ricardo,

    I just wanted to say, “Thank you” for your work and your posting of it. I really appreciate it when a great programmer / designer / thinker / all-around-smart person shares their knowledge with others who are farther back on path.

    This truly is outstanding, and I appreciate it so very, very much.

    Thank You,

    -David.

  4. Hey there, I’ve used this in one example and it works awesomely, however. When I try to implement with a database and add an object. I just get a white page with the Json returned. Do you know what may be causing this?

    1. Hi,

      The white page gives me the impression that the jquery event is not properly binded. If you are generating the list dynamically on through java script, make sure you re-bind the events so they are properly handled.I hope this helps,

      -Ricardo

  5. Hi.

    I have used your examples for update and delete for many pages on the current site and they work great, however today I ran into a snag and was wondering if you had any thoughts. I can’t find anything like this in my normal search areas.

    I have a checkbox on the grid that I am updating, and it will not change the checked property of the box UNLESS I step through the code. When I do, it updates as expected and when I remove all breakpoints it does nothing to the checkbox.

    I am using the .html(data.Object.AllowTexts) that is returned with the Json result and the value is correct. I then test for true or false and update the checked property of the checkbox on closest(“tr”). Can you think of any reason it would work with breakpoints and not without?

    Thanks,
    Kaisha

  6. Hi,

    First of all, thank you very much for posting this code!

    I have tried to implement your code, and I’m pretty sure I’ve copied it exactly from the source code, and updated accordingly. However when I click on the Update button, my browser (IE9) asks to download a file, which basically contains the JSON. I have googled this problem, but nothing came up that would indicate what I have done wrong. It’s also never hitting the updateSuccess function. I’m sure its something simple, but have spent ages double checking my code. Any pointers would be most appreciated.

    Many thanks

    Dave

    1. Managed to fix it! I wasn’t including the validate jQuery scripts! Hopefully this will help someone if they have the same problem.

      Dave

      1. I’ve been having a hard time with the same issue for days now! Good thing I saw your comment! Thank you!!!

  7. I haven’t discoved why yet but the modal validation doesn’t seem to work with jquery version 1.7.2. After stuggling with it for a while, I changed to the version in your demo (1.5.1) and it worked great.

  8. Hi sir! Thank you for this tutorial. I followed the steps you specified and tried to reproduce the same output on my project but I can’t seem to reproduce the same results.

    If you have some spare time, can you please help me with my problem? I have a post at stackoverflow.com. I would highly appreciate if you can visit it for me. Thank you very much!

    http://stackoverflow.com/questions/11425003/asp-net-mvc-popup-partial-view-on-add-form-crud-issue/11465494#11465494

    1. I’ve replied on StackOverflow. However, I could not determine the problem as you didn’t post the javascript code. Just make sure you are creating the proper javascript bindings.

      1. Hi Sir Covo! Thanks for the response! I have already updated my thread and included my javascript code. Kindly check. Thank you very much! 🙂

      2. Hi Sir Covo! I already fixed my problem by adding the validator javascripts on my masterpage (i saw Dave’s comment above). Now I have a question, I am not using tables and foreach to display the items on my page. Rather, I am using a webGrid. Is there any way to refresh the partial view containing my webGrid after the updateSuccess method has been called? Thank you very much!!!!

      3. That will depend on which webGrid you are using. You’ll have to see what methods they offer to update the grid and its contents.

      4. Hello, This example is very helpful but could you show on the callback refreshing a partial view inside a div rather than updating the raw html?

      5. Yes I agree it would be great to so a refresh, especially n my case because I am adding a new tab that is built in the controller and passed back in the model, so it would be nice to see how you do a refresh of the partial view.

  9. Nice article. I have noticed one issue. When I try your demo in IE9, the update works fine but if i click the ‘Edit’ button for the one I just updated, the pop up contains the information prior to the first edit.Seems to work fine with other browsers. Any idea why the changes do not make it to the pop up in IE?

    1. Ed, it might be related to browser caching. Maybe specifying no-caching on the action would do the trick (sorry, really busy at the moment and can’t test it my self). Please share with everyone if you get a positive result.

      Thanks,

  10. Thanks for this tutorial. I used your code in my project but I have an error
    $(“.editLink”).button(); object doesn’t support this property or method (0x800a01b6).

    Can you help me please

    1. Atefb,

      The class button is part of jquery UI, as long as you have the proper reference it should work. Notice that I just use the jquery ui button because it looks better. You can use a regular html button if you want.

      Hope this helps,

  11. Hello,
    Thanks for this tutorial.
    I tried to get the same thing to send a message from the connected user to other users in my website. But I had this problem
    $(“.sendlink”).button(); object doesn’t support this property or method

  12. Hey Ricardo thanks a lot for this.

    But I’m having a problem, when I implement you solution whit a database I get a blank page with the json printed on it. It´s not entering the updateSuccess function. Do you know why is this happening?

    1. memeonline,

      When you get the json printed on the screen is most likely because the javascript events are not being binded correctly. Review that you have all references and that you are binding your objects correctly.

      Hope this helps,

  13. Its awesome example i was looking for this for past two months… But i have issue. I have downloaded code just mapped with Database Employee table and I tried to Edit. I am getting Json result but function updateSuccess(data) doesnt gets called can you help me

    1. This normally happens when then javascript events are not binding correctly. Review that you have all references and that you are binding your objects correctly.

  14. Thank you immensely. After trawling through umpteen sites where the author simply acts like a demi god, offering half baked answers and patronising commentary, an example cleanly presented, that opens first time and illustrates, quite beautifully, what you are trying to communicate. Many thanks indeed!

  15. Sir nice post please help me as to why my updateSuccess doesnt work?? I click on Edit Button where i am just fetching Data of a particular Employee. When i click on Update updatesucess doesnt work

    1. Shalin,

      This normally happens when when the events are not binded correctly. Make sure you have a good reference to jQuery and that the code for binding to the click event is properly called. I recommend using the developer tools of browsers to debug your javascript and see if there are any errors.

      -Ricardo

      1. Now I have solved the issue of popup , but got in stuck with json result object . In my case rather than redirecting to index , it redirects to a blank page with json object displaying all my edited parameters . What could be the reason for it not redirecting to index with Update Success ?

  16. I have copied the same events still I see json string of parameters , In my scenario , updateSuccess function is not called . From the controller Http post action it directly redirects to json string page . Why it didn’t move to updateSuccess function ?

    1. Check if there are any errors when you originally load the page; then check if there are any erros when the modal view comes up. Errors could prevent your bindings from happening.

      1. First of all I have commented the unobtrusive validation line in script , as I was getting errors for $.valdation . Then I save the data in my DB .After that I just need to pass my object to updateSuccess function . Don’t know why the function is not called ?

      2. Without more information about the code, I can’t really help further. I would check all the references are passed in, confirm versions of jquery, jquery validate, jquery validate unobstrusive, etc.

        It is not normal that $.validation fail if you have all references in place.

      3. The problem I think is That your data comes from repository where it is arranged as list , but my data comes from database as an object , and then we try to return that object to json . Following which I get json string like

        {“Success”:true,”Object”:{“id”:1,”userid”:3,”description”:”test9″, etc.

        What’s your say in this ?

      4. Shalin, it has nothing to do with where the data comes from. I use a list on the example but I use databases on all my live implementations.

        I think you have an error on the bindings or other javascript errors; that is the most common cause of the issue you are describing.

    2. Hello shalin, did you find a solution for your problem: {“Success”:true,”Object”:{“id”:1,”userid”:3,”description”:”test9″, if you have the solution you can contact me please because I have the same problem

      best regards

  17. Hi. Thanks a lot for this article. I created a small app implementing your method, and everything works great except the JSON data gets returned in a file format instead of updating my data using the ‘updateSuccess’ function. I’ve posted my question in stack-overflow. http://stackoverflow.com/questions/15742617/asp-net-mvc-json-response-sends-me-a-file-instead-of-updating-the-jqueryui Please have a look at it. Any help would be greatly appreciated. Thanks.

  18. Hi Sir your code is very helpful to me. Can you write a post for creating also. It will be very helpful for freshers.
    Thank you sir

      1. Hi Ricardo,
        there’s no problem :-), in the first moment the link did not work, I dont know why….. Now It’s all ok, THX for your reply..

        Stefano

  19. I downloaded your source code and opened it in VS2012 and updated it. After updating, everything works except the edit function in Modal. When you click Edit FOR THE FIRST TIME, the modal gets the values to edit and clicking on save button updates the record. But when you click the EDIT for the same record second time, the modal does not hit the ActionResult Get method while debugging so the form is showing the old (previous) values not the ones which are updated in the last call.

  20. Hi Ricardo,

    I can’t get the JsonResponseFactory option. Can you let me know wath reference I need?

    Thank
    Claudio

  21. Hello sir, thank you for your post it really helped me a lot, I problem i facing is after post to the action it redirecting to blank page with json result. can you help me out in this

  22. I am trying to add new record it works fine only problem i am facing is OnSuccess = “updateSuccess” not firing instead redirecting to blank page

  23. sir thank you very for you king reply please can we have some sample for insert(create new)
    i added and it solved

  24. Thank you very sir, add ajax jquery.unobtrusive-ajax.min.js works fine, can we have some example for insert are redirect after insert

Leave a comment