2012-02-23 9 views
1

MVC3とC#でコードを記述しています。例外とカスタム例外が発生したときに、ユーザーフレンドリーなメッセージをユーザーに送信します。 JSONとjQueryのポップアップボックスを使用することを考えています。 これを行う方法を教えてもらえますか?このトピックに関するチュートリアルや記事はありますか?JSONとjQueryを使用したMVC3の例外処理とステータスメッセージ

EDIT:

私はIExceptionFilterを拡張するカスタムActonFilterを作成したいです。カスタムフィルタは例外をキャッチし(スローされた場合)、カスタムクラスShowMessage(ex)を返します。カスタムクラスは、目的のメッセージを含むJSON結果を返します。 jQueryには、ポップアップボックスにメッセージが表示されるパーサーがあります(例外がある場合)。

+0

いつあなたはそれをしたいですか?そして、なぜデフォルトの検証メカニズムが十分なものではないのですか? – jgauffin

+0

説明を入力してください。 –

+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を介して何かが起こっているかどうか、またその結果を成功/失敗の結果として知らせる。

また、それを呼び出すとコンテンツ

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

この後半を返す、のActionResultを使用することにより同様の効果などを実現することができます - 私はちょうどその場でそれを書いただけの擬似コードとしてそれを考えるが、小さな微調整で動作するはずです。

うまくいけば、これはあなたに助けであり、私は、誰かが私に私も自分自身をより良くするのが大好きだより良い方法を示すことができる場合、私は、しかし、間違って何かをするために笑われません:)

+0

ありがとうございました。私が探しているものではありませんが、とても役に立ちます。個人的には私のコントローラーにHTMLとjavascriptを書くのが好きではありません。 –

+1

担当者に感謝します。私は自分のコントローラーにHTMLまたはJavaScriptを書いているのではなく、より洗練されたソリューションもありますが、それは私にとって非常に役立っています。同様の機能を実現するより良い方法です。あなたは正確に何を探していますか?あなたがもう少し精巧にできるなら、私は助けることができるかもしれません。 – jhartzell

+0

元の質問にさらに情報を追加しました。私はそれが今より明確であることを願っています:) –

関連する問題