0

我已经关注了这篇文章,但我的解决方案唯一有效的是错误消息警报。: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参数的值传递给它,回调函数将在其中执行它job(根据给定的 id 调用一些 View)。

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

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

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

        return View();
    }
4

1 回答 1

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();
    }
}
于 2013-09-10T13:36:13.353 回答