使用JSON和jQuery在MVC3中进行异常处理和状态消息

时间:2012-02-23 13:21:20

标签: c# jquery json asp.net-mvc-3

我在MVC3和C#中编写代码。我想在发生异常和自定义异常时向用户发送用户友好的消息。我正在考虑使用JSON和jQuery弹出框。 你能告诉我怎么做吗?是否有关于此主题的教程或文章?

修改

我想创建扩展IExceptionFilter的自定义ActonFilter。自定义过滤器捕获异常(如果它们被抛出)并返回自定义类ShowMessage(ex)。自定义类返回包含所需消息的JSON结果。在jQuery中有一个解析器,它显示带有消息的弹出框(如果有异常)。

1 个答案:

答案 0 :(得分:1)

如果我似乎能正确理解你的问题,有很多方法可以做到这一点。

我的控制器看起来像这样:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult ContactUs(DatabaseModelExtensions.ContactRequest model) // Pass          model of which I am submitting a form against to retrieve data inside this HTTPPost Controller
    {
        // Create database object to map extension class to it.
        ContactRequest NewEntry = new ContactRequest();

        if (ModelState.IsValid)
        {
            // Map database object to the model passed and then insert.
            NewEntry.Name = model.Name;
            NewEntry.Email = model.Email;
            NewEntry.Message = model.Message;
            NewEntry.Timestamp = System.DateTime.Now;

            // Insert new entry into database for historical tracking
            NewEntry.Insert();

            // Clear modelstate (clearing form fields)
            // ModelState.Clear(); -- Does not work with an Ajax call - requires postback.

            // Email user about their contact request and also send admins a summary of the contact request.
            // Create new UserMailer Object so that we can invoke this class and work with it's functions/properties.
            var Mailer = new UserMailer();

            // Instantiated the 'msg' variable that will allow for us to invoke Mailer.ContactSubmission(), this function passes a series of parameters so that we can reference them inside
            // our UserMailer.cs class which then gets passed to a mail template called ContactSubmission.cshtml under the Views -> UserMailer folder
            var msg = Mailer.ContactSubmission(firstName: model.Name, email: model.Email, telephone: model.Telephone);

            // Same as above except we will be sending out the management notification.
            var msg1 = Mailer.AdminContactSubmission(firstName: model.Name, email: model.Email, datetime: System.DateTime.Now, message: model.Message, telephone: model.Telephone);

            // Invoke the .Send() extended function that will actually execute everything to send an SMTP mail Request.
            msg1.Send();
            msg.Send();


            // Return our content back to the page asynchronously also create a quick snippet of js to slide the message up after a few seconds.               
            return Content(new MvcHtmlString(@"
                                    <div id='sendmessage'>
                                        Your message has been sent, Thank you!
                                    </div>
                                    <script type='text/javascript'>
                                       setTimeout(function () { jQuery('#results').slideUp('fast') }, 3000);
                                    </script>").ToString());
        }
            // Return our Error back to the page asynchronously.
        return Content(new MvcHtmlString(@"
                                    <div id='errormessage'>
                                        An error has occured, please try again in a few moments!
                                    </div>
                                    <script type='text/javascript'>
                                       setTimeout(function () { jQuery('#results').slideUp('fast') }, 3000);
                                    </script>").ToString());
    }

我的观点看起来像是:

<div id="results">Content would be returned in place of this div.</div>
@using (Ajax.BeginForm("ContactUs", "Home",
        new AjaxOptions
        {
            LoadingElementId = "loading",
            OnBegin = "DisableForm('contactform')",
            UpdateTargetId = "results",
            OnSuccess = "resetForm('contactform'); removeLoading()"
        }, new { @id = "contactform" }))
    {       
        @Html.ValidationSummary(true)           
        <div id="results">

        </div>
        <ul class="cform">
            <li><label for="name">Name:</label>             
            @Html.TextBoxFor(Model => Model.Name, new { @name = "name", @id = "name", @class = "fancyinput reginput" })
            @Html.ValidationMessageFor(Model => Model.Name)
            </li>
            <li><label for="email">E-mail:</label>
            @Html.TextBoxFor(Model => Model.Email, new { @name = "email", @id = "email", @class = "fancyinput reginput" })
            @Html.ValidationMessageFor(Model => Model.Email)
            </li>
             <li><label for="telephone">Telephone:</label>
            @Html.TextBoxFor(Model => Model.Telephone, new { @name = "telephone", @id = "telephone", @class = "fancyinput reginput" })
            @Html.ValidationMessageFor(Model => Model.Telephone)
            </li>
            <li><label for="message">Message:</label>
            @Html.TextAreaFor(Model => Model.Message, new { @name = "message", @id = "message", @class = "fancyinputarea", @rows = "10", @cols = "62" })
            @Html.ValidationMessageFor(Model => Model.Message)
            </li>
            <li><input type="submit" value="Submit" class="btn" name="submit"/><img id="loading" style="display: none;" src="../../Content/img/loading27.gif" alt="Loading..." /></li>
        </ul>
    }

这是一个简单的联系页面示例,其中包含ajax的完整功能,并通过带有动画gif的css背景的加载div警告用户何时发生某些事情,并让他们知道他们的结果成功/失败。< / p>

通过使用ActionResult,调用它并返回Content

,您也可以获得类似的效果
 public ActionResult SubmitForm(int id)
 {
      return Content(new MvcHtmlString("<div>test test</div>").ToString());
 }

 and the jQuery AJAX side of things would be;

 $.ajax({
   type: 'POST',
   url: @Url.Action("SubmitForm","VotingController"),
   data: { id : @Model.UserId },
   success: success, // Javascript function to call back on success.
   dataType: dataType // data type expected back from the server
 });

这个后半部分 - 只是将它视为伪代码,因为我只是在动态编写它,但应该使用小的调整。

希望这对你有所帮助,我不会因为做错事而受到嘲笑,但是,如果我这样做了,有人可以告诉我一个更好的方式,我也愿意为自己做得更好:)