使用ajax将数据传递给控制器

时间:2013-05-16 08:40:34

标签: asp.net-mvc-3 jquery

如何通过ajax调用将以下数据传递给控制器​​

Stack Trace: at ApricaCRMEvent.Controllers.HomeController.ErrorBadRequest() in E:\Aprica\ApricaSVN\Project\Internal\Aprica\CRM_New\Integrated\ApricaCRMEvent\ApricaCRMEvent\Controllers\HomeController.cs:line 46 at lambda_method(Closure , ControllerBase , Object[] ) at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.b__12() at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<>c__DisplayClass17.b__14() at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) at System.Web.Mvc.Controller.ExecuteCore() at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) at System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) at System.Web.Mvc.MvcHandler.<>c__DisplayClass6.<>c__DisplayClassb.b__5() at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.b__0() at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.b__7(IAsyncResult _) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End() at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag) at System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) at System.Web.Mvc.MvcHandler.<>c__DisplayClasse.b__d() at System.Web.Mvc.SecurityUtil.b__0(Action f) at System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) 
从这样的视图中调用ajax

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <center>
    <h2>Sorry, An Error Occured.</h2>
    </center>
    <% if (ViewBag.username == "admin")
       { %>

       <% if (Model.Exception != null ) { %>
            <p>
              Controller: <%= Model.ControllerName %>
            </p>
            <p>
              Action: <%= Model.ActionName %>
            </p>
            <p>
              Message: <%= Model.Exception.Message%>
            </p>
            <p>
              Stack Trace: <%= Model.Exception.StackTrace%>
            </p>
        <% } %>

    <%}
       else
       { %>
        <center>
            <h3>Sorry for inconvinience caused. You can report this error to administrator.</h3>
            <br />
            <input type="button" id="postError" value="Report Error" />
        </center>
    <%} %>

    <script type="text/javascript">
        $(document).ready(function () {
            $("#postError").click(function () {
                var vcontroller= "<%= Model.ControllerName %>";
                var vaction= "<%= Model.ActionName %>";
                var vmessage= "<%= Model.Exception.Message%>";
                var vstacktrace= "<%= Model.Exception.StackTrace%>";
                $.ajax({
                    url: '/Error/Error/',
                    type: "POST",
                    data: {
                        controller: vcontroller,
                        action: vaction,
                        message: vmessage,
                        stackTrace: vstacktrace    
                    },
                    dataType: "json",
                    success: function (data) {
                        alert(data.result);
                    },
                    error: function () {
                        alert("Some Error Occured while reporting Error.");
                    }
                });
            });
        });
    </script>
    </asp:Content>

代码var vstacktrace= "<%= Model.Exception.StackTrace%>";

中出现问题
at ApricaCRMEvent.Controllers.HomeController.ErrorBadRequest() in E:\Aprica\ApricaSVN\Project\Internal\Aprica\CRM_New\Integrated\ApricaCRMEvent\ApricaCRMEvent\Controllers\HomeController.cs:line 46 at lambda_method(Closure , ControllerBase , Object[] ) at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.b__12() at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<>c__DisplayClass17.b__14() at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) at System.Web.Mvc.Controller.ExecuteCore() at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) at System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) at System.Web.Mvc.MvcHandler.<>c__DisplayClass6.<>c__DisplayClassb.b__5() at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.b__0() at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.b__7(IAsyncResult _) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End() at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag) at System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) at System.Web.Mvc.MvcHandler.<>c__DisplayClasse.b__d() at System.Web.Mvc.SecurityUtil.b__0(Action f) at System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

如果有人有想法请帮助......

1 个答案:

答案 0 :(得分:0)

如果此#submit是提交按钮,请确保通过从回调中返回false来取消默认操作:

<script type="text/javascript">
$(document).ready(function () {
    $('#submit').click(function () {
        $.ajax({
            url: '/Error/Error/',
            type: 'POST',
            data: { 
                sendEmail: true 
            },
            success: function (data) {
                alert(data.result);
            },
            error: function () {
                alert("Some Error Occured while reporting Error.");
            }
        });

        return false;  // <!-- this is the important bit
    });
});
</script>

现在您的控制器操作可能如下所示:

[HttpPost]
public ActionResult Error(bool sendEmail)
{
    ...
}

显然你也可以传递其他信息:

data: { 
    message: 'some message',
    sendEmail: true 
},

并且控制器操作也可以有这个message参数。

您的代码的另一个问题是您已将网址硬编码到控制器操作中:

url: '/Error/Error/'

这非常糟糕,因为这样您就不会利用您的路由,这意味着如果您更改Global.asax中路由定义的模式,则此URL将不再有效。此外,如果您在虚拟目录中的IIS上部署正确的URL现在将是'/ YouAppName / Error / Error'。为了将所有这些考虑在内,你不应该像这样硬编码网址,而是使用网址助手来生成它们:

url: '<%= Url.Action("Error", "Error") %>'

显然,这假设javascript在你的视图中是内联的,你可以使用帮助器。如果它在一个单独的javascript文件中(显然这是正确的方法),那么你可以使用HTML5 data- *属性来存储url作为DOM的一部分,但是用帮助器生成。

例如,假设这个#submit是你DOM中的一些div:

<div id="submit">
    Click me to submit
</div>

您可以为其添加data-url属性:

<div id="submit" data-url="<%= Url.Action("Error", "Error") %>">
    Click me to submit
</div>

现在在你单独的js文件中你可以使用这个属性:

$('#submit').click(function () {
    $.ajax({
        url: $(this).data('url'),
        ...

另一方面,如果此#submit是表单的提交按钮,则只需使用相应表单的action即可。在这种情况下,不要订阅提交按钮的.click事件,而是订阅表单的.submit事件:

$(document).ready(function () {
    $('#your_form_id').submit(function () {
        $.ajax({
            url: this.action,
            type: this.method,
            data: { 
                sendEmail: true 
            },
            success: function (data) {
                alert(data.result);
            },
            error: function () {
                alert("Some Error Occured while reporting Error.");
            }
        });

        return false;  // <!-- this is the important bit
    });
});

更新:

为了安全地将某些模型属性序列化为javascript变量,您应该使用JSON序列化程序:

var vstacktrace = <%= new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model.Exception.StackTrace) %>