genxgeek
genxgeek

Reputation: 13357

How to refresh a view calling RedirectToAction?

How can I refresh a view within a controller method calling redirect (or equivalent)?

View (Index.cshtml):

@model ViewModel

@Html.EditorFor(model => model.First)
@Html.EditorFor(model => model.Last)

@Html.EditorFor(model => model.Junk)

// call is invoked to PerformMagic as such:

onComplete: function (event, queueID, fileObj, response, data) 
{
   $.ajax(
   { url: '@Url.Action("PerformMagic","Home")',
       data: { first: $("#fname").val() },
      })
   }

Junk.cshtml (Editor Template)

 @model Models.Junk

 <div>
    @Html.LabelFor(model => model.ID)
    @Html.EditorFor(model => model.ID)
</div>
<div>
    @Html.LabelFor(model => model.Name)
    @Html.EditorFor(model => model.Name)
    @Html.ValidationMessageFor(model => model.Name)
</div>

Controller:

// Called from jquery client
public string PerformMagic(string Id)
{
    ViewModel model = dbContext.GetPersistedView();
    model.Junk.Add(new junk);

    // I need to update my view here but this doesn't update the view (model updates fine)....
    // ...after a refresh on the browser of course the new junk in the model is displayed.
    return RedirectToAction("Index", model);  
}

Upvotes: 2

Views: 3125

Answers (1)

gdoron
gdoron

Reputation: 150263

It looks like you are making an ajax request.

You can't redirect an ajax request! what you should do is return Json values of the model and in the client side update the page:

public string PerformMagic(string Id)
{
    ViewModel model = dbContext.GetPersistedView();
    model.Junk.Add(new junk);

    return Json(model);
}

jQuery:

onComplete: function(event, queueID, fileObj, response, data) {
    $.ajax({
        url: '@Url.Action("PerformMagic","Home")',
        data: {
            first: $("#fname").val()
        },
        success: function(response) {
            $('#First').val(response.First);
            $('#Last').val(response.Last);
            $('#Junk').val(response.Junk);...
        }
    })
}​

Upvotes: 5

Related Questions