2012-02-23 6 views
1

MVC3 및 C#에서 코드를 작성하고 있습니다. 예외 및 사용자 지정 예외가 발생할 때 사용자에게 친숙한 메시지를 보내고 싶습니다. JSON 및 jQuery 팝업 상자를 사용할 생각입니다. 이 작업을 수행하는 방법을 알려주시겠습니까? 이 주제에 대한 자습서 또는 문서가 있습니까?JSON 및 jQuery를 사용하여 MVC3의 예외 처리 및 상태 메시지

편집 :

내가 IExceptionFilter를 확장 사용자 정의 ActonFilter을 만들려고합니다. 사용자 정의 필터는 예외 (catch 된 경우)를 catch하고 사용자 정의 클래스 ShowMessage (예)를 반환합니다. 맞춤 클래스는 원하는 메시지가 포함 된 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> 
    } 

을 사용자가 애니메이션 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과 자바 스크립트를 쓰는 것을 좋아하지 않는다. –

+1

담당자에게 감사드립니다. 나는 내 컨트롤러에 HTML이나 자바 스크립트를 쓰는 데 큰 팬이 아니며 아마도 더 우아한 해결책이있을 것입니다. 그러나 그것은 저에게 매우 도움이되었으며 아직 찾을 수 없습니다. 유사한 기능을 수행하는 더 좋은 방법입니다. 당신은 정확히 무엇을하기를 원합니까? 좀 더 정교하게 설명하면 도움이 될 것입니다. – jhartzell

+0

원래 질문에 더 많은 정보를 추가했습니다. 나는 그것이 지금 더 분명하다라고 생각한다 :) –