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

发布于 2025-01-08 21:59:10 字数 289 浏览 1 评论 0原文

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

编辑:

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

I am writing my code in MVC3 and C#. I want to send user friendly messages to the user when exceptions and custom exceptions occur. I am thinking of using JSON and jQuery popup boxes.
Can you tell me how to do this? Is there a tutorial or article on this topic?

EDIT:

I want to create custom ActonFilter that extends IExceptionFilter. The custom filter catches exceptions (if they are thrown) and returns custom class ShowMessage(ex). The custom class returns JSON result containing the desired message. In the jQuery there is a parser that shows the popup box with the message (if there is an exception).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浮生未歇 2025-01-15 21:59:10

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

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

    [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 警告用户何时发生某些情况并让他们知道他们的结果成功/失败。

您还可以通过使用 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
 });

This 后半部分来实现类似的效果以及更多效果 - 只需将其视为伪代码,因为我只是即时编写它,但应该进行一些小的调整。

希望这对您有帮助,并且我不会因为做错事而被嘲笑,但是,如果我这样做并且有人可以向我展示更好的方法,我也很乐意改善自己:)

There are a number of ways to go about doing this if I seem to understand your question correctly.

My controller would look like this:

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

My view would then look something like:

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

This is a simple example of a contact page with full functionality for ajax and warning the user of when something is happening via a loading div with a css background of an animated gif and also letting them know their outcome success/fail.

You can also achieve a similar effect and more by using an ActionResult, calling that and returning 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
 });

This later half - just consider it as pseudo code as I just wrote it up on the fly but should work with small tweaks.

Hopefully this is of help to you and I don't get laughed at for doing something incorrectly, however, if I did and someone can show me a better way I would love to better myself as well :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文