나는 우리의 웹 사이트에 등록하기 위해 초대장을 보내는 데 사용되는 다음과 같은 간단한보기가 있습니다. 이것은 관리자 전용보기에 있으며 이메일 주소가 채워지면 관리자가 클릭하여 초대장을 보낼 수 있습니다. 코드는내 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()
을 주석으로 처리하면 컨트롤러에 내 게시물이 실행되지 않습니다! 이 경우 내가 뭘 잘못하고 있니?
당신 'View'를 돌려 주지만 당신은 JS의 결과를 가지고 아무것도하지 않습니다 –
점검 페이지 초기화가로드 될 때 다시보기. 페이지가 새로 고침 될 때까지 뷰 백이 다시 검사되지 않습니다. SendInvite 이메일에서 obj를 반환 한 다음 아약스 성공시 해당 obj를 확인하십시오. – Botonomous
'View()'를 반환하고'ViewBag'를 사용하는 대신'Json (new {Message = "Some messge"});을 반환합니다 –