2

I have an MVC 4 View that contains a form and a partial view. The main view contains information about a product and the partial view contains images of the product.

What I would like to do is to have the partial view contain it's own form which the images would be displayed on. If I submit this form to a controller action method, modify the model it's based on and then have the action method refresh the partial view, will just the partial view section of my main view change and not the main view itself? If not, is there a better way to do what I'm trying to do. I just want to update the partial view section of the main view.

Hosea146
  • 7,412
  • 21
  • 60
  • 81

1 Answers1

7

If you want to update just the Partial View, you should retrieve the data using an AJAX call. That way you call a Controller that will return you the View (in this case Partial View) that you need. Example:

CSHTML:

<div id="myPartialViewDiv">
    @{Html.RenderPartial("myPartialView", Model);}
</div>

JS:

searchAdmin = function () {

    var URL = "myController/myAction";

    $.get(URL, { "optionalArg": optionalArg }, function (data) {
        $("#myPartialViewDiv").html(data);
    })
}

myController:

public JsonResult myAction(string optionalArg)
{
    // do something...

    return this.Json(whatIwantToReturn.ToList(), JsonRequestBehavior.AllowGet);
}
Axel Prieto
  • 535
  • 10
  • 20
  • Thanks Zed. Instead of my action method returning a JsonResult, can it return an ActionResult. Which, in this case, I would just return the model the partial view is based on. I'm still pretty new at all this. – Hosea146 May 21 '13 at 14:50
  • Yes, you can see how to do that in this [post](http://stackoverflow.com/questions/4730777/mvc-return-partial-view-as-json) – Axel Prieto May 21 '13 at 14:56