在 MVC3 中从客户端调用服务器端函数

call server-side function from client-side in mvc3

本文关键字:调用 服务器端 函数 客户端 MVC3      更新时间:2023-09-26

我已经关注了这篇文章,但唯一适用于我的解决方案的是错误消息警报。 :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)。

布乌特,我只得到"哈哈,这不行!菜鸟!"警报消息。:D有什么建议吗?

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

public ActionResult Media()
    {
        //do some stuff here 
        return View();
    }
你必须

修改你的方法

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

参考 MVC Razor 添加以下方法 ASP.NET:如何在控制器操作中呈现 Razor 部分视图的 HTML

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