ASP.NET MVC - 渲染PartialView使用AJAX? [英] ASP.NET MVC - Render PartialView with AJAX?

查看:197
本文介绍了ASP.NET MVC - 渲染PartialView使用AJAX?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天早些时候我张贴另一个帖子里@Darin季米特洛夫帮了我很大的,但是再一次,我stucked ... 我的javascript调用AddWebsite的ActionResult这做它的工作,因为它应该,但在$阿贾克斯(误差函数),因为

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

不是有效的JSON。

isn't valid JSON.

我遇到的例子,人们使用类似

I've come across examples where people use something like

RenderPartialViewToString(partialview, model);

和投掷到一个JSON对象......但它太的hackish如果你问我..是不是有一个更简单的方法来做到这一点?

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?

...和code:

// DashboardController.cs

// 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

// 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!

推荐答案

在特定的情况下,我认为这个问题是你的JavaScript code。您指定的dataType (这是函数需要什么样的反应来分析)为 JSON 。根据你贴你应该有 HTML 的dataType ,它应该解决您的问题中的作用。这没有什么错这样做,(你没有使用JSON的一切)。

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

这篇关于ASP.NET MVC - 渲染PartialView使用AJAX?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆