寻找使用 ajax 将 MVC 5 视图发布到控制器的正确方法
Posted
技术标签:
【中文标题】寻找使用 ajax 将 MVC 5 视图发布到控制器的正确方法【英文标题】:Looking for proper way to use ajax to post an MVC 5 View to a controller 【发布时间】:2019-03-31 21:00:41 【问题描述】:我有一个 MVC 5 应用程序,我正在尝试使用 ajax 来执行发布,以避免页面在发布后完全重新加载。该网页基本上是一个联系页面。我正在为此 Web 应用程序使用 Visual Studio 2017。我还在为 CaptchaMVC.MVC5 使用 Nuget 包。 MVC 5 Application存在以下问题:
我无法从我拥有的 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")
这是感谢视图:
@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>
【问题讨论】:
您的代码有多个错误。但是为什么你的控制器方法中有return RedirectToAction(...)
- ajax 调用无法重定向(ajax 的全部意义在于保持在同一页面上)所以不清楚你要做什么
我想删除这篇文章,但收到一条消息,如果我这样做了,我会被暂停,只是忽略这篇文章。对我来说,在 mvc 和 C# 中完成这一切而不用 javascript 会更简单。
【参考方案1】:
您的 javascript 有很多错误。我看不到您如何在 js 中定义模型。您的操作返回 HTML,但您定义了 contentType json。要在 javascript 中序列化,您应该使用 JSON.stringify
【讨论】:
我要重做问题和代码。最终会有所帮助的是,如果我能找到一个完整的示例(不是像我在网上看到的那样到处都是 sn-p),展示如何制作 MVC 5 表单以将数据从视图发布到控制器而不导致整体页面刷新。我认为这是使用 Ajax 完成的,但我没有可遵循的工作示例。我尝试使用基于名为 Contact 的 MVC 模型的强类型视图来执行此操作,该模型被传递到视图中并用“模型”一词引用。一个完整示例的 URL 会很好。以上是关于寻找使用 ajax 将 MVC 5 视图发布到控制器的正确方法的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 ajax get 将数据从 View 传递到 Controller 或使用参数在 mvc 中发布
将多个参数从 ajax post 传递到 asp.net mvc 控制器