1

我正在尝试在联系表单后发布一条消息,向用户表明他们的消息在他们单击提交按钮后已发送。我不想重定向到不同的页面或在我的 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?

4

2 回答 2

0

您可以在包含消息的页面上放置一个隐藏的 div。

然后,当您的表单提交后,捕获按钮的单击事件,并使用它来显示隐藏的消息。

如果您需要代码示例,请告诉我。发布您的表格将有助于我们更具体地回答您。

于 2015-06-23T16:19:03.610 回答
0

要仅在成功发送表单时显示成功消息,我建议在控制器的 POST 操作中的 ViewBag 中设置一个值,然后如果您希望仍然显示相同的页面,则返回相同的页面。然后,您可以在 View 本身上放置一条 If 语句来测试 ViewBag 变量是否包含值,如果是,则显示消息。

控制器:

[HttpPost]
public ActionResult YourAction(YourModel m)
{
    //Do stuff to send the contact form
    ...
    if(error)
    {
        ViewBag.Message = "There was a problem sending the form.";
    }
    else
    {
        ViewBag.Message = "The form was sent successfully!";
    }
    return View(m);
}

看法:

@if(ViewBag.Message != null)
{
    <div>@ViewBag.Message</div>
}

这使您可以在告诉用户结果之前检查表单是否已成功发布到服务器上,并且仅在设置了 ViewBag.Message 时才显示一条消息。请注意,您可以拥有任意数量的 ViewBag 变量,并且可以随意命名它们……只要记住您在哪个地方使用哪个变量即可。

编辑:

在评论之后,这也可以使用 AJAX 调用来完成。为简单起见,我将使用 jQuery .post() 方法。

在脚本中:

<script>
    $(document).on('click', "#buttonId", function() {
        var nameText = $("#IdOfNameField").val();
        var emailText = $("#IdOfEmailField").val();
        var messageText = $("#IdOfMessageField").val();
        $.post('@Url.Content("~/Controller/AJAXPostContactForm")',//the url to post to
            {name: nameText, email: emailText, message: messageText }, //these are values to be sent to the action
            function(){ //this is the success function
                $("#successMessage").val("Form posted successfully.");
            }
        )
        .fail(function() {//failure function
            alert("Something went wrong.");
        });
    }
</script>

控制器:

public void AJAXPostContactForm(string name, string email, string message)
{
    try
    {
        //do stuff with the information passed into the action
    }
    catch(exception e)
    {
        //Handle errors. If error thrown, Ajax should hit fail block in script
    }
    finally
    {
        //do any cleanup actions
    }
}

看法:

<div id="successMessage"></div>

我没有测试过这段代码,但理论上它应该可以工作。单击特定按钮时,它将从表单字段中获取值,将这些值发布到控制器中的专用 ActionResult,然后返回有关所发生情况的消息。

于 2015-06-23T16:52:17.310 回答