我正在尝试在联系表单后发布一条消息,向用户表明他们的消息在他们单击提交按钮后已发送。我不想重定向到不同的页面或在我的 HTTP Post 操作方法中返回不同的视图。如何在 ASP.NET MVC 框架中执行类似的操作?
以下是我的代码示例:
@*contactus.cshtml*@
@model MySite.Models.ContactModel
@using (Html.BeginForm())
{
<div class="col-md-6">
<div class="form-group">
@Html.TextBoxFor(model => model.Name})
<p>@Html.ValidationMessageFor(model => model.Name)</p>
</div>
<div class="form-group">
@Html.TextBoxFor(model => model.Email)
<p>@Html.ValidationMessageFor(model => model.Email)</p>
</div>
<div class="form-group">
@Html.TextAreaFor(model => model.Message)
<p>@Html.ValidationMessageFor(model => model.Message)</p>
</div>
<div class="col-lg-12">
<button type="submit">Send Message</button>
</div>
</div>
}
@*ContactModel.cs*@
public class ContactModel
{
[Required(ErrorMessage = "* Please enter your name.")]
[StringLength(100, MinimumLength=3, ErrorMessage="* Please enter your full name.")]
public string Name { get; set; }
[Required]
[EmailAddress(ErrorMessage="* Not a valid email address.")]
public string Email { get; set; }
[Required]
public string Message { get; set; }
}
我的主页/索引页面上现在只有一个联系我们表格,我不想将其重定向到任何其他页面。我想在Send Message
按钮正下方显示一条消息,但我不确定如何使用以下操作方法进行操作:
@*HomeController.cs*@
public ActionResult Index(ContactModel model)
{
if (ModelState.IsValid)
{
// this is my helper library, for brevity, I'm not copying it.
EmailHelper emailService = new EmailHelper();
bool success = emailService.SendEmail(model.Name, model.Email, model.Message);
return Content(success ? "success" : "no...something went wrong :(");
} else {
return View(model);
}
}
现在这个控制器将返回Content
替换我整个页面的字符串,我希望在我的联系表单下方返回字符串。另外,我在同一个 html 页面上有两个部分,其中联系表单作为第二个部分,当我返回 View(model) 时,它会自动重定向到第一部分,这并不理想......我如何告诉控制器仅在 POST 方法之后将其重定向到第二部分?另外,我觉得如果它不返回整个页面会更有效......那么有没有办法只返回一个Message字符串到div?