简体   繁体   中英

ASP.NET MVC Show View after Ajax call to a Controller

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!

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()

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); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM