【问题标题】:call server-side function from client-side in mvc3从 mvc3 中的客户端调用服务器端函数
【发布时间】:2013-09-10 13:22:39
【问题描述】:

我已关注this post,但我的解决方案唯一有效的是错误消息警报。 :D

我的 js-ajax 代码:

$(document).ready(function () {
    $('a').click(function (e) {
        var data = { 'id': $(this).attr("id") };
        var dataVal = JSON.stringify(data);

        $.ajax({
            type: "POST",
            url: "@Url.Action("ActionName", "ControllerName")", 
            contentType: "application/json; charset=utf-8",
            data: dataVal,
            dataType: "json",
            success: function (id) {
                alert(data.d);
                alert("yay! it works!");
            },
            error: function(id){
                alert("haha, it doesn't work! Noob!");
            }
        });
        return false;
    });
});

它位于正文的末尾,因此它会在所有其他 html 内容呈现后加载。

这是我在控制器中的回调函数:

[HttpPost]
public ActionResult Hello(string id)
{
    return RedirectToAction(id);
}

和 HTML 锚标记:

<a href="#" style="float:left; font-size:13px;" id="pageName">Read more</a>

所以,我想要的是,在任何点击锚标记链接时,这个 JS 将被触发并从服务器端调用该函数,并将 id 参数的值传递给它,回调函数将在其中完成其工作(即根据给定的 id 调用某个 View)。

Buuuuut,我得到的只是“哈哈,这行不通!菜鸟!”警报消息。 :D 有什么建议吗?

更新一些代码 RedirectToAction 是框架中的一个方法,它重定向到另一个动作。在这种情况下,我会重定向到一个会调用我某个视图的操作,例如这个:

public ActionResult Media()
    {
        //do some stuff here 

        return View();
    }

【问题讨论】:

  • 这个$(document).ready(function () {}); 本身就是你保证它会在DOM 准备好时执行。您可以将其放置在您想要的任何位置,而不仅仅是在页面末尾。
  • 您应该返回JsonResultRedirectToAction(id) 是什么?向我们显示您要重定向的代码。
  • 这不是你的问题,但无论如何都是错误的:success: function (id)。它应该是success: function (data),因为您在内部依赖它:alert(data.d);
  • @Satpal - 我更新了我的帖子。
  • @MelanciaUK - 仍然无法正常工作。

标签: javascript html ajax asp.net-mvc-3 callback


【解决方案1】:

你必须修改你的方法

public ActionResult Media()
{
    //do some stuff here 

    return View();
}

类似

public JsonResult Media()
{
    //do some stuff here 
    return Json(new
                {
                    myData = RenderPartialViewToString("ViewName", optionalModel),
                    errorMessage = error
                });
}   

参考ASP.NET MVC Razor: How to render a Razor Partial View's HTML inside the controller action添加如下方法

protected string RenderPartialViewToString(string viewName, object model)
{
    if (string.IsNullOrEmpty(viewName))
        viewName = ControllerContext.RouteData.GetRequiredString("action");

    ViewData.Model = model;

    using (StringWriter sw = new StringWriter()) {
        ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
        ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
        viewResult.View.Render(viewContext, sw);

        return sw.GetStringBuilder().ToString();
    }
}

【讨论】:

  • 很好,但为什么不是 JsonResult 而不是 ActionResult?
  • @MelanciaUK,欢呼ActionResult 可以处理Json 因此离开它。还更新了答案
猜你喜欢
  • 1970-01-01
  • 2017-06-27
  • 2018-05-10
  • 1970-01-01
  • 2015-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-17
相关资源
最近更新 更多