ASP.NET MVC - Render PartialView with AJAX?

Earlier today I posted another post in which @Darin Dimitrov helped me a lot, but I was stuck again ... My javascript calls AddGoSportEventResult, which does this job as it should, however the error function in $ .ajax () always works , because the

return PartialView(ListPartialView, MapUserToViewModel); 

Invalid JSON.

I met examples where people use something like

RenderPartialViewToString(partialview, model);

and throws it into a JSON object ... but it is too hacky if you ask me .. is there an easier way to accomplish this?

... And the code:

//DashboardController.cs

[HttpPost]
public ActionResult AddWebsite(CreateWebsiteViewModel website)
{
    if (!ModelState.IsValid)
    {
        throw new HttpException(400, "Client-side validation failed.");
    }

    if (string.IsNullOrWhiteSpace(website.URL))
    {
        throw new ArgumentNullException("URL", "The URL cannot be empty nor contain only whitespaces.");
    }

    using (_session.BeginTransaction())
    {
        _session.Query(new AddWebsite(_contextProvider.GetUserSession.UserId, website.URL));
        _session.Transaction.Commit();
    }

    return PartialView(ListPartialView, MapUserToViewModel);
}

//MyJs.js

$("#testform").live('submit', function () {

    var test = { URL: $("#URL").val() };

        $.ajax({
            url: "/Dashboard/AddWebsite",
            type: "POST",
            data: JSON.stringify(test),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                alert("TRIG");
                $("#content").html(data);
            },
            error: function () {
                alert("Error");
            }
        });

    return false;
});

Thanks in advance!

+3
source share
2 answers

, javascript. dataType ( , ) json. html dataType, . ( JSON ).

+4

dataType contentType ? test , , Asp.net MVC - , .

, jQuery , JSON .

+1

Source: https://habr.com/ru/post/1788832/


All Articles