Samantha J T Star
Samantha J T Star

Reputation: 32758

What's the most "MVC" standard way to refresh / update part of an MVC page?

I have a web page that shows a table of data. My page has jQuery on some elements such that when the elements change an Ajax call is made to the database and the element is updated in the database.

I also have a need to sometime completely refresh the data grid. It would seem to me there are two ways of doing this:

1) Use Ajax to call my controller action, check if is an Ajax request using Request.IsAjaxRequest, return HTML.Partial to the javascript that called the Ajax and have that update the HTML. I have this method 90% working already.

Previous stackoverflow question

2) Use the following:

<div id="#thingy">@Html.Action("Detail", new { ac, me })</div>  
$('#thingy').load("@Server.JavaScriptStringEncode(Url.Action("Detail", new { ac, me }))"); 

Now I am still trying to get the first method to work but also looking at the second method and thinking it looks a lot easier.

I want to write code that works but also code that conforms most to the MVC way of doing things. With this in mind. Which might be the best method? One thing that concerns me is the @Server.Java... code. I have never seen this before and I am wondering how this is handled with MVC, does all the normal security get applied?

Upvotes: 2

Views: 10043

Answers (1)

jim tollan
jim tollan

Reputation: 22485

melissa,

I'd almost definitely stick with a partialview (and @RenderPartial()) IF the model in the view is the same as that in the partialview, otherwise you could opt for the @RenderAction() helper to invoke data refreshes across your view where the base data type varies significantly from the base view data type.

You'll know from your app which approach is best suited to the use case in question, but definitely the RenderPartial() would be the approach to major on, where ajax updates are required at a later point in the piece to update the html in the div.

[edit] - here's how i would see this set out in practice:

// this is a div contained within the main Detail.cshtml view
<div id="#thingy">@Html.RenderPartial("_Detail", Model)</div>

this would automatically on 1st pass populate the div from the Model against a partialview called _Detail.cshtml. Subsequently, you would invoke your ajax to target this same div (#thingy) via an action which returned the partialview and model as per the above.

i.e.:

public ActionResult Detail(string ac, string me) {     
   vm.AdminDetails = _link.Detail(ac + me).ToList();      
   if (Request.IsAjaxRequest())         
      return PartialView("_Detail", vm);     
   return View(vm); 
}

Hope this makes sense.

good luck

Upvotes: 5

Related Questions