0

如何通过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)

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

4

1 回答 1

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 硬编码到控制器操作中:

url: '/Error/Error/'

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

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) %>
于 2013-05-16T08:45:28.557 回答