4
votes

I have a View with a submit form: when I click it a jquery/ajax function is called. This function has to encode the View Model, call a Controller action and show the View returned. Now, this is my function:

<script type="text/javascript">
function Analyze() {
    var urlact = '@Url.Action("Analysis")';
    var model = '@Html.Raw(Json.Encode(Model))';
    $.ajax({
        data: model,
        type: "POST",
        url: urlact,
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            //WHAT HERE??
        }
    });
}
</script>

And the Analysis action is a kind of

public ViewResult Analysis(IEnumerable<Azienda> aziende) {
        Debug.WriteLine(aziende.Count());
        return View(aziende);
    }

Returning a View! How can I display that View on success:function(data)? I tried changing dataType to html and calling on success alert(data) but I had problems with the encoded model, I tried commenting the contentType line but same model-encoding issue.

Does someone know how to do that? A js/query/ajax workaround-trick is fine, too.

Thanks you all!

2
Do you want to replace the whole page or just part of it? - Yan Brunet
I want to replace all the page! - Jack88PD
Why not just a regular submit on the form then ? - Yan Brunet
Because that causes a postback and a page refresh - Alan Macdonald
Did you get anywhere with this? I want to do something similar - Alan Macdonald

2 Answers

0
votes

Use

return PartialView()

instead of

return View()

in your controller. Then in the success function in your ajax call, use the jQuery .html() function to update the element you wish to update in your html. See Query.html() and View() vs. PartialView()

0
votes

Create a separate partial view with aziende as its model and return this in your Analysis action and then append the result to a div in your view:

//action returning a partial view
public ActionResult Analysis(IEnumerable<Azienda> aziende) 
{
    Debug.WriteLine(aziende.Count());
    return PartialView("_partialView", aziende);
}

//then append the result to a div in your javascript
success: function (data) {
    $("#some-div").html(data); 
}