2014-12-09 3 views
0

나는 우리의 웹 사이트에 등록하기 위해 초대장을 보내는 데 사용되는 다음과 같은 간단한보기가 있습니다. 이것은 관리자 전용보기에 있으며 이메일 주소가 채워지면 관리자가 클릭하여 초대장을 보낼 수 있습니다. 코드는내 ViewBag에 구멍이 있습니다. Liza님께,

@using (Html.BeginForm("Upload", "Tools", FormMethod.Post, 
     new { @class = "form-horizontal", role = "form" })) 
    { 
     @Html.AntiForgeryToken() 
     <h2>Invite Users</h2> 
     <div class="form-group"> 
      @Html.LabelFor(m => m.EmailAddress, new { @class = "col-md-2 control-label" }) 
      <div class="col-md-10"> 
       @Html.TextBoxFor(m => m.EmailAddress, 
        new { @class = "form-control", id = "email" }) 
       @Html.ValidationMessageFor(m => m.EmailAddress) 
      </div> 
     </div> 
     <div class="form-group"> 
      @Html.Label("Access To", new { @class = "col-md-2 control-label" }) 
      <div class="col-md-10"> 
       @Html.DropDownList("Product", new SelectList(
        new List<Object> { 
         new { Text = "D", Value = "D" }, 
         new { Text = "U", Value = "U" }, 
         new { Text = "All", Value = "All" }}, 
         "Value", 
         "Text"), 
         new { @class = "form-control", id = "product" }) 
      </div> 
     </div> 
     <div class="form-group"> 
      <div class="col-md-offset-2 col-md-10"> 
       <span class="label label-danger">@ViewBag.FailedMessage</span> 
       <span class="label label-success">@ViewBag.SuccessMessage</span> 
      </div> 
     </div> 
     <div class="form-group"> 
      <div class="col-md-offset-2 col-md-10"> 
       <input type="button" value="Invite User" class="btn btn-primary" /> 
      </div> 
     </div> 
    } 

가 선택 콤보 박스 선택과 클릭 다시 버튼 컨트롤러에 게시하려면, 나는 이것에 대한 제어 방법은

입니다

<script> 
    $(function() { 
     $("input[type=button]").click(function() { 
      var data_email = $('#email').val(); 
      var data_product = $('#product option:selected').text(); 
      $.ajax({ 
       url: 'Tools/SendInvite', 
       type: 'POST', 
       data: { email: data_email, product: data_product }, 
       success: function (result) { 
       } 
      }); 
     }); 
    }); 
</script> 

다음 자바 스크립트를 사용

[HttpPost] 
[AllowAnonymous] 
public async Task<ActionResult> SendInvite(
    string email, string product) 
{ 
    ApplicationUser user = null; 
    if (ModelState.IsValid) 
    { 
     user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); 
     if (user.IsAdmin != null && (bool)user.IsAdmin) 
     { 
      string key = String.Empty; 
      string subMsg = String.Empty; 
      var accessDB = new AccessHashesDbContext(); 
      switch (product) { /* do stuff */ } 

      // Send email. 
      try 
      { 
       await Helpers.SendEmailAsync(new List<string>() { email }, null, "my message string"); 
       ViewBag.FailedMessage = String.Empty; 
       ViewBag.SuccessMessage = String.Format(
        "Invitation successfully sent to \"{0}\"", 
        email); 
      } 
      catch (Exception) 
      { 
       ViewBag.SuccessMessage = String.Empty; 
       ViewBag.FailedMessage = String.Format(
        "Invitation to \"{0}\" failed", 
        email); 
      } 
     } 
    } 
    return View(); 
} 

이 코드는 작동하여 내 이메일 템플릿을 필요한 수신자에게 보냅니다. 그러나 이메일이 전송되었거나 ViewBag을 통해 전송되지 않았 음을 알리고 싶습니다. 이 코드는 작동하는 것처럼 보이지만, ViewBag은 비어 있고 메시지가 표시되지 않습니다. 여기서 내가 뭘 잘못하고 있니?

감사합니다.


편집. 아래의 @ yhax의 대답을 사용하여 다음과 같은 시도 된 해결책을 찾았습니다. 나는 지금 내 컨트롤러에서 나는 내 시야에서 내 자바 스크립트에서

[HttpPost] 
[AllowAnonymous] 
public async Task<ActionResult> SendInvite(string email, string product) 
{ 
    ApplicationUser user = null; 
    string result = "{\"invite_result\":\"{0}\",\"invite_success\":\"{1}\"}"; 
    if (ModelState.IsValid) 
    { 
     user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); 
     if (user.IsAdmin != null && (bool)user.IsAdmin) 
     { 
      string key = String.Empty; 
      string subMsg = String.Empty; 
      var accessDB = new AccessHashesDbContext(); 
      switch (product) { /* do stuff */ } 

      // Send email. 
      try 
      { 
       await Helpers.SendEmailAsync(new List<string>() { email }, null, "my message string"); 
       result = String.Format(result, 
        String.Format("Invitation successfully sent to \"{0}\"", email), 
        "true"); 
       return Content(result); 
      } 
      catch (Exception) 
      { 
       result = String.Format(result, 
        String.Format("Invitation to \"{0}\" failed", email), 
        "false"); 
       return Content(result); 
      } 
     } 
    } 
    result = String.Format(result, "Invite Failed", "false"); 
    return Content(result); 
} 

을 가지고 있습니다

<script> 
    $(function() { 
     $("input[type=button]").click(function() { 
      var data_email = $('#email').val(); 
      var data_product = $('#product option:selected').text(); 
      $.ajax({ 
       url: 'Tools/SendInvite', 
       type: 'POST', 
       data: { email: data_email, product: data_product }, 
       success: function (result) { 
        var obj = JSON.parse(jsontext); 
        if (obj.invite_success == "true") { 
         $('#fail_message').val(""); 
         $('#success_message').val(obj.invite_result); 
        } 
        else { 
         $('#fail_message').val(obj.invite_result); 
         $('#success_message').val(""); 
        } 
       }, 
       error: function() { 
        alert("Invite Failure"); 
       } 
      }); 
     }); 
    }); 
</script> 

이 항상 error 조건을 타격하고 경고를 보여줍니다. 이 error: function()을 주석으로 처리하면 컨트롤러에 내 게시물이 실행되지 않습니다! 이 경우 내가 뭘 잘못하고 있니?

+2

당신 'View'를 돌려 주지만 당신은 JS의 결과를 가지고 아무것도하지 않습니다 –

+1

점검 페이지 초기화가로드 될 때 다시보기. 페이지가 새로 고침 될 때까지 뷰 백이 다시 검사되지 않습니다. SendInvite 이메일에서 obj를 반환 한 다음 아약스 성공시 해당 obj를 확인하십시오. – Botonomous

+0

'View()'를 반환하고'ViewBag'를 사용하는 대신'Json (new {Message = "Some messge"});을 반환합니다 –

답변

1

난 당신이 뭔가를하려는 생각 :

컨트롤러 :

[HttpPost] 
[AllowAnonymous] 
public async Task<ActionResult> SendInvite(
    string email, string product) 
{ 
    ApplicationUser user = null; 
    if (ModelState.IsValid) 
    { 
     user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); 
     if (user.IsAdmin != null && (bool)user.IsAdmin) 
     { 
      string key = String.Empty; 
      string subMsg = String.Empty; 
      var accessDB = new AccessHashesDbContext(); 
      switch (product) { /* do stuff */ } 

      // Send email. 
      try 
      { 
       await Helpers.SendEmailAsync(new List<string>() { email }, null, "my message string"); 
       return Content(String.Format("Invitation successfully sent to \"{0}\"", email)); 
      } 
      catch (Exception) 
      { 
       return Content(String.Format(
        "Invitation to \"{0}\" failed", 
        email)); 
      } 
     } 
    } 
// you could redirect to another action, or return some other message 
    return Content("not valid etc etc"); 
} 

하고 여기에서 반환 된 메시지와 함께 뭔가를 할 수 :

<script> 
    $(function() { 
     $("input[type=button]").click(function() { 
      var data_email = $('#email').val(); 
      var data_product = $('#product option:selected').text(); 
      $.ajax({ 
       url: 'Tools/SendInvite', 
       type: 'POST', 
       data: { email: data_email, product: data_product }, 
       success: function (result) { 
// do something here... show a box with the message, whatever you like 
console.log(result); 
       } 
      }); 
     }); 
    }); 

+0

대단히 감사합니다. 나는이 물건에 완전히 멍청하다. HTML 요소에서 데이터를 가져 오는 방법을 알고 있지만 자바 스크립트에서 내 레이블과 같은 속성을 설정하는 방법은 무엇입니까? 이것에 대한 추가 정보 또는 링크는 대단히 감사하겠습니다 ... – MoonKnight

+0

HTML 요소에 ID가 설정되어 있는지 확인하면됩니다. 예를 들어

+0

마지막으로, 결과에 따라 두 가지 레이블 색상을 사용하고 싶습니다. 위의 코드를 사용하면 하나의 문자열 객체 만 전달합니다. 각 레이블에 하나씩 두 개의 문자열 객체를 어떻게 다시 전달합니까? – MoonKnight

관련 문제