开发者

ASP.NET MVC - Render PartialView with AJAX?

开发者 https://www.devze.com 2023-02-07 07:39 出处:网络
Earlier today I posted another post where @Darin Dimitrov helped me great, however once again I\'m stucked...

Earlier today I posted another post where @Darin Dimitrov helped me great, however once again I'm stucked... My javascript calls the AddWebsite ActionResult which does it job as it should, however the error function in the $.ajax() is always firing since

return PartialView(ListPartialView, MapUserToViewModel); 

isn't valid JSON.

I've come across examples where people use something like

RenderPartialViewToString(partialview, model);

and throws it into a JSON object... but it's just too "hackish" if you ask me.. isn't 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!


In your particular instance I think the problem is with your javascript code. You are specifying the dataType (which is what the function expects to parse in the response) as json. Based on the Action you posted you should have html as the dataType and it should solve your problem. There's nothing wrong with doing that (you don't have to use JSON for everything).


Simple data

Why are you setting dataType and contentType in the first place? Since your object test is very simple you can just provide it as is and it will be consumed by Asp.net MVC without any problems and you will return your partial view.

Complex data

If your object would be more complex then you could use a different jQuery plugin that will make it possible to send complex JSON objects without strigification.

0

精彩评论

暂无评论...
验证码 换一张
取 消