寻找使用ajax将MVC 5视图发布到控制器的正确方法

时间:2018-10-27 08:05:37

标签: javascript c# jquery asp.net-mvc asp.net-ajax

我有一个MVC 5应用程序,我正在尝试使用ajax进行发布,以避免页面在发布后完全重新加载。该网页基本上是一个“联系”页面。我正在将Visual Studio 2017用于此Web应用程序。我还在CaptchaMVC.MVC5的Nuget包中使用。 MVC 5应用程序存在以下问题:

我无法从拥有的javascript中的Message TextArea Web元素中读取值。

我在Ajax代码中创建的json对象到达ContactController并输入ContactCreate操作方法,但是视图中的Java脚本中的值未出现。它们都是空的。

我正在尝试将ajax成功和错误结果发送到元素,但是没有发生。我不确定如何在ajax调用中执行此操作。

对于解决所列问题的任何建议,我将不胜感激。预先感谢。

这是联系人模型:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace rgmsite.Models
{
  public class Contact
  {
    [Required(ErrorMessage="The name of the person submitting this form is required")]
    [DisplayName("Your Name")]
    [StringLength(128, MinimumLength = 2)]
    public string Name { get; set; }

    [Required(ErrorMessage = "The email address to reply back to is required")]
    [StringLength(128, MinimumLength = 5)]
    public string Email { get; set; }

    [Required(ErrorMessage = "The subject of this contact request is required")]
    [StringLength(128, MinimumLength = 2)]
    public string Subject { get; set; }

    [Required(ErrorMessage = "A message describing why you are submitting a contact request is required")]
    [StringLength(250, ErrorMessage = "The number of characters allowed for a message is 5 to 250", MinimumLength=5)]
    public string Message { get; set; }
  }
}

这是联系人控制器:

using rgmsite.Models;
using System.Web.Mvc;
using CaptchaMvc.HtmlHelpers;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

namespace rgmsite.Controllers
{
  public class ContactController : Controller
  {
    [HttpGet]
    public ActionResult ContactNew()
    {
      return View();
    }

    [HttpPost]
    public ActionResult ContactCreate(Contact aContact)
    {
      if (ModelState.IsValid)
      {
        // Code for validating the CAPTCHA  
        if (this.IsCaptchaValid("Captcha is not valid"))
        {
          return RedirectToAction("ThankYouPage", aContact);
        }
      }

        ViewBag.ErrMessage = "Error: captcha is not valid.";

      return View("ContactNew", null, aContact);
    }

    public ActionResult ThankYouPage(Contact aContact)
    {
      return View(aContact);
    }
  }
}

这是ContactNew视图:

@model rgmsite.Models.Contact
@using CaptchaMvc.HtmlHelpers;
@using CaptchaMvc;


@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<!--
<script src="~/Scripts/jquery-1.10.2.js"></script>
-->

<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>

@using (Ajax.BeginForm("ContactCreate",
                        "Contact",
                        null,
                        new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "UpdateArea1" },
                        new { id = "ContactFormId" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset id="ContactForm">
        <legend>Contact</legend>

        <div id="UpdateArea1">
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            <div class="form-group row">
                @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-4 col-sm-3 col-md-4 col-lg-2 col-xl-2" })
                <div class="col-8 col-sm-9 col-md-8 col-lg-10 col-xl-10">
                    @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control", id = "NameId" } })
                    @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group row">
                @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-4 col-sm-3 col-md-4 col-lg-2 col-xl-2" })
                <div class="col-8 col-sm-9 col-md-8 col-lg-10 col-xl-10">
                    @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control", id = "EmailId" } })
                    @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group row">
                @Html.LabelFor(model => model.Subject, htmlAttributes: new { @class = "control-label col-4 col-sm-3 col-md-4 col-lg-2 col-xl-2" })
                <div class="col-8 col-sm-9 col-md-8 col-lg-10 col-xl-10">
                    @Html.EditorFor(model => model.Subject, new { htmlAttributes = new { @class = "form-control", id = "SubjectId" } })
                    @Html.ValidationMessageFor(model => model.Subject, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group row">
                @Html.LabelFor(model => model.Message, htmlAttributes: new { @class = "control-label col-4 col-sm-3 col-md-4 col-lg-2 col-xl-2" })
                <div class="col-8 col-sm-9 col-md-8 col-lg-10 col-xl-10">
                    @Html.TextAreaFor(model => model.Message, 4, 40, new { htmlAttributes = new { @class = "form-control", id = "MessageId" } })
                    @Html.ValidationMessageFor(model => model.Message, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="row" >
                <div class="col-sm-6">
                    <div >
                        <p class="Error">
                            @ViewBag.ErrMessage<br />
                        </p>
                        <div id="PostResults">
                            Results go here.
                        </div>
                    </div>
                </div>
            </div>

            <p>
                @Html.MathCaptcha()
            </p>
            <br />

        </div>
    </fieldset>


    <div class="col-md-offset-2 col-md-10">
        <input type="button" id="PostButton" value="Send Contact Info" />
    </div>


}
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

<script type="text/javascript">
    $(function () {
        $("#PostButton").click(function () {
            var Contact = {};
            Contact.Name    = $("#NameId").val();
            Contact.Email   = $("#EmailId").val();
            Contact.Subject = $("#SubjectId").val();
            Contact.Message = $("#MessageId").val();
            $.ajax(
                {
                    type: "POST",
                    url: "/Contact/ContactCreate",
                    data: '{Contact: ' + JSON.stringify(Contact) + '}',
                    contentType: "application/json; charset=utf-8",
                    datatype: "json",
                    success: function (data) {
                        var result = $('<div />').append(data).find('#PostResults').html();
                        $('PostResults').html(result);
                    },
                    error: function (data) {
                        var result = $('<div />').append(data).find('#PostResults').html();
                        $('PostResults').html(result);
                    },

                });
        });
    });

</script>



@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")

}

这是ThankYou视图:

@model rgmsite.Models.Contact

@{
    ViewBag.Title = "Thank You";

      Layout = "~/Views/Shared/_Layout.cshtml";

}
<p>
    <h2>Thank You</h2>
</p>
<div>
    <h4>Summary of Contact Information Received</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.Name)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Name)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Email)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Email)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Subject)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Subject)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Message)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Message)
        </dd>

    </dl>
</div>

1 个答案:

答案 0 :(得分:0)

您的JavaScript有很多错误。我看不到如何在js中定义模型。您的操作返回HTML,但您定义了contentType json。要使用javascript进行序列化,应使用JSON.stringify