Tutorial :Use different updatetargetid based on view


I have a web page which display a list of items in a HTML table. Above the list is a form which allows the user to add a new item to the list via AJAX (using Ajax.BeginForm). When the data is posted to the controller via AJAX I add the new item to the database backend and generate a new table row via a Partial View which then gets appended to the exisiting table.

When the form to add new items however contains errors, I want to render the form back to the web browser and display that.

So here is the question: Is it possible to specify the UpdateTargetId from within the controller? At the moment whatever View I return from the controller gets inserted in the same target, but I would like to update a different target (ie. different UpdateTargetId) based on whatever view was returned from the controller.

Any help would be appreciated...


i think a workaround could be using json and checking the result in callback function. this is how it would look like

function handleAjax(response) {                var result = response.get_response().get_object();              var isSuccess = result[0].isSuccess;              if(isSuccess = "true")              {                 $("#resultdiv").html(result[0].html);              }              else              {                  $("#formdiv").html(result[0].html);              }             }  

in your action u can write something like

public ActionResult SaveRecord(Entity entity)  {     if(ModelState.IsValid(){     return Json(new{isSuccess = true, html = PartialView("RowViewName")});      }     else    {       return json (new{isSuccess = false, html = PartialView("FormViewName")})    }  }  

i just ran into the same problem today and could not find "legal" way of doing this. i think this simple workaround should get it done. at the moment code is completely untested. i m gonna implement this tomorrow morning.
Note: Please read this blog post for alternative solution


Basically what you want is to return 2 different results depending on certain conditions while you're making an ajax request. Unfortunately that's not possible with the actual implementation of AjaxForm. You can update only a single region of your form.

A possible workaround to this problem may be creating a partial view with the form to update and return the partial view from the controller, then you create the new row in the table with plain old javascript on the onSuccess event.


I think another idea can be redirecting on the server to another controller/action with

RedirectToAction(new {controller="home", action="index", id=931,variable="abc"});  

so if the form contains an error RedirectToAction ... which even could contain another PartialView which could be placed in another DIV...

just a thought...

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »