使用 Ajax 将视图中的多个实例传递给控制器
Posted
技术标签:
【中文标题】使用 Ajax 将视图中的多个实例传递给控制器【英文标题】:Pass multiple instance in view to controller using Ajax 【发布时间】:2015-09-27 16:45:10 【问题描述】:我尝试使用 AJAX 将 List<Theatres>
从视图发送到控制器
每个theates
都有一个 TheatresName (string)、TheatresNumber (int)、HomeCinemaID (int)、RowAmount (int)。
这里是型号代码:
public class MovieTheaters
[Key]
public int MovieTheatersID get; set;
public int HomeCinemaID get; set;
public string TheatersName get; set;
public int NumberHall get; set;
public int RowAmount get; set;
//FK .
public virtual HomeCinema HomeCinema get; set;
public virtual ICollection<Rows> Rows get; set;
用户输入他需要多少个剧院,然后 for 循环提供了创建它们的选项。
查看代码:
@model CimenaCityProject.Models.MovieTheaters
@
ViewBag.Title = "Create";
<h2>Create New Theatres</h2>
@html.AntiForgeryToken()
@
int? maxNumberOfTheatres = ViewBag.number;
if (!maxNumberOfTheatres.HasValue)
maxNumberOfTheatres = 1;
@using (Html.BeginForm("Create", "Theatres", FormMethod.Post, new name = "TheatresForm", id = "TheatresForm" ))
@Html.ValidationSummary(true)
<table>
<tbody>
@for (int i = 0; i < maxNumberOfTheatres.Value; i++)
<tr>
<td id="NewTheaters">
@ViewBag.ErrorMassage
<div style="position:relative; top: 0px; left: 205px; width: 278px;">
@string.Format("Theares Number 0", i + 1)
</div>
<div>
<br />
<div class="form-group">
@Html.LabelFor(model => model.HomeCinemaID, "HomeCinemaID", new @class = "control-label col-md-2" )
<div class="col-md-10">
@Html.DropDownList("HomeCinemaID")
@Html.ValidationMessageFor(model => model.HomeCinemaID)
</div>
<br />
</div>
<div class="form-group">
@Html.LabelFor(model => model.TheatersName, new @class = "control-label col-md-2" )
<div class="col-md-10">
@Html.EditorFor(model => model.TheatersName)
@Html.ValidationMessageFor(model => model.TheatersName)
</div>
<br />
</div>
<div class="form-group">
@Html.LabelFor(model => model.NumberHall, new @class = "control-label col-md-2" )
<div class="col-md-10">
@Html.EditorFor(model => model.NumberHall)
@Html.ValidationMessageFor(model => model.NumberHall)
</div>
<br />
</div>
<div class="form-group">
@Html.LabelFor(model => model.RowAmount, new @class = "control-label col-md-2" )
<div class="col-md-10">
@Html.EditorFor(model => model.RowAmount)
@Html.ValidationMessageFor(model => model.RowAmount)
</div>
</div>
</div>
</td>
</tr>
</tbody>
</table>
<div class="form-group">
<div class="col-lg-push-9">
<input type="submit" name="Create" value="Create" id="Create" />
</div>
</div>
<div id="divLoading" style="display: none; align-items: center">
<img src="~/Image/Elements/ajax-loader.gif" />
</div>
<div id="divResult"></div>
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts
@Scripts.Render("~/bundles/jqueryval")
Ajax 代码:
<script type="text/javascript">
$(document).on('#TheatresForm' ,function ()
var NewTheaters = [];
$('table tbody tr td').each(function ()
NewTheaters.push(
HomeCinemaID: $('#HomeCinemaID').val(),
TheatersName: $('#TheatersName').val(),
NumberHall: $('#NumberHall').val(),
RowAmount: $('#RowAmount').val()
);
);
$('#divLoading').show()
$.ajax(
url: '@Url.Action()',
type: 'POST',
traditional : true,
data: JSON.stringify(NewTheaters),
contentType: 'application/json; charset=utf-8',
success: function (result)
success(result)
,
error: function (result)
alert(result.responseText + "Error")
$('#divLoading').hide()
);
function success(result)
alert("success")
$('#divResult').html(result)
$('#divLoading').hide()
);
控制器代码
// GET: /Theatres/Create
public ActionResult Create(int? id, int? number)
if (id == null)
ViewBag.HomeCinemaID = new SelectList(db.HomeCinemas, "HomeCinemaID", "CinemaName");
number = 1;
ViewBag.number = number;
else
ViewBag.HomeCinemaID = new SelectList(db.HomeCinemas.Where(x => x.HomeCinemaID == id).ToArray(), "HomeCinemaID", "CinemaName");
ViewBag.number = number;
ViewBag.ErrorMassage = "";
return View();
// POST: /Theatres/Create
[HttpPost]
public ActionResult Create( List<MovieTheaters> NewTheaters)
foreach (var movietheaters in NewTheaters)
if (db.Theaters.Where(x => x.TheatersName == movietheaters.TheatersName && x.HomeCinemaID == movietheaters.HomeCinemaID).FirstOrDefault() == movietheaters)
ViewBag.ErrorMassage = "You cant add this Theatres again. Choose another name.";
ViewBag.HomeCinemaID = new SelectList(db.HomeCinemas.Where(x => x.HomeCinemaID == movietheaters.HomeCinemaID).ToArray(), "HomeCinemaID", "CinemaName", movietheaters.HomeCinemaID);
return View(movietheaters);
else
if (ModelState.IsValid)
db.Theaters.Add(movietheaters);
db.SaveChanges();
return RedirectToAction("Create", "Rows", new id = movietheaters.MovieTheatersID, rwcpcty = movietheaters.RowAmount, last = 1 );
ViewBag.ErrorMassage = "Try again later";
ViewBag.HomeCinemaID = new SelectList(db.HomeCinemas, "HomeCinemaID", "CinemaName", movietheaters.HomeCinemaID);
return View(movietheaters);
ViewBag.ErrorMassage = "Try again later";
ViewBag.HomeCinemaID = new SelectList(db.HomeCinemas, "HomeCinemaID", "CinemaName");
return View();
每次它给我一个 null .. 我必须做什么?
【问题讨论】:
你能提供使用的控制器代码和型号吗?? 好的,我编辑了帖子 它到底在哪里抛出异常?在视图中还是在控制器中?在控制器中返回一个 JsonResult 怎么样:return Json(Data, JsonRequestBehavior.AllowGet); 你试过“数据:NewTheaters:NewTheaters”。不要把它串起来。这对我有用。 您甚至在您的页面上使用了多个同名的 id。你不能那样做。 【参考方案1】:好的。非常感谢@Rohit Arora 和 @Hemant Bhagat 这里的完整答案非常好。
代码控制器:
// GET: /Theatres/Create
public ActionResult Create(int? id, int? number)
if (id == null)
ViewBag.HomeCinemaID = new SelectList(db.HomeCinemas, "HomeCinemaID", "CinemaName");
number = 1;
ViewBag.number = number;
else
ViewBag.HomeCinemaID = new SelectList(db.HomeCinemas.Where(x => x.HomeCinemaID == id).ToArray(), "HomeCinemaID", "CinemaName");
ViewBag.number = number;
ViewBag.ErrorMassage = "";
return View();
// POST: /Theatres/Create
[HttpPost]
public ActionResult Create( List<MovieTheaters> NewTheaters)
foreach (var movietheaters in NewTheaters)
if (db.Theaters.Where(x => x.TheatersName == movietheaters.TheatersName && x.HomeCinemaID == movietheaters.HomeCinemaID).FirstOrDefault() == movietheaters)
ViewBag.ErrorMassage = "You cant add this Theatres again. Choose another name.";
ViewBag.HomeCinemaID = new SelectList(db.HomeCinemas.Where(x => x.HomeCinemaID == movietheaters.HomeCinemaID).ToArray(), "HomeCinemaID", "CinemaName", movietheaters.HomeCinemaID);
return View(movietheaters);
else
if (ModelState.IsValid)
db.Theaters.Add(movietheaters);
db.SaveChanges();
return RedirectToAction("Create", "Rows", new id = movietheaters.MovieTheatersID, rwcpcty = movietheaters.RowAmount, last = 1 );
ViewBag.ErrorMassage = "Try again later";
ViewBag.HomeCinemaID = new SelectList(db.HomeCinemas, "HomeCinemaID", "CinemaName", movietheaters.HomeCinemaID);
return View(movietheaters);
ViewBag.ErrorMassage = "Try again later";
ViewBag.HomeCinemaID = new SelectList(db.HomeCinemas, "HomeCinemaID", "CinemaName");
return View();
查看代码:
@model List<CimenaCityProject.Models.MovieTheaters>
@
ViewBag.Title = "Create";
var selectlist = (SelectList)ViewBag.HomeCinemaID;
<h2>Create New Theatres</h2>
@Html.AntiForgeryToken()
@
int? maxNumberOfTheatres = ViewBag.number;
if (!maxNumberOfTheatres.HasValue)
maxNumberOfTheatres = 1;
@using (Html.BeginForm("Create", "Theatres", FormMethod.Post))
@Html.ValidationSummary(true)
<table>
<tbody>
@for (int i = 0; i < maxNumberOfTheatres.Value; i++)
<tr>
<td id="NewTheaters" style="width:700px">
@ViewBag.ErrorMassage
<div style="position:relative; top: 0px; left: 205px; width: 278px;">
@string.Format("Theares Number 0", i + 1)
</div>
<div>
<br />
<div class="form-group">
@Html.LabelFor(model => model[i].HomeCinemaID, "HomeCinemaID", new @class = "control-label col-md-2" )
<div class="col-md-10">
@Html.DropDownListFor(model => model[i].HomeCinemaID, selectlist)
@Html.ValidationMessageFor(model => model[i].HomeCinemaID)
</div>
<br />
</div>
<div class="form-group">
@Html.LabelFor(model => model[i].TheatersName, new @class = "control-label col-md-2" )
<div class="col-md-10">
@Html.EditorFor(model => model[i].TheatersName)
@Html.ValidationMessageFor(model => model[i].TheatersName)
</div>
<br />
</div>
<div class="form-group">
@Html.LabelFor(model => model[i].NumberHall, new @class = "control-label col-md-2" )
<div class="col-md-10">
@Html.EditorFor(model => model[i].NumberHall)
@Html.ValidationMessageFor(model => model[i].NumberHall)
</div>
<br />
</div>
<div class="form-group">
@Html.LabelFor(model => model[i].RowAmount, new @class = "control-label col-md-2" )
<div class="col-md-10">
@Html.EditorFor(model => model[i].RowAmount)
@Html.ValidationMessageFor(model => model[i].RowAmount)
</div>
</div>
</div>
</td>
</tr>
</tbody>
</table>
<div class="form-group">
<div class="col-lg-push-9">
<input type="button" name="Create" value="Create" id="Create" onclick="SaveTheatre()" />
</div>
</div>
<div id="divLoading" style="display: none; align-items: center">
<img src="~/Image/Elements/ajax-loader.gif" />
</div>
<div id="divResult"></div>
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts
@Scripts.Render("~/bundles/jqueryval")
Ajax 代码:
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.sigmacape.unobtrusive-1.1.2.js"></script>
<script type="text/javascript">
function SaveTheatre()
$.ajax(
url: '@Url.Action()',
type: 'POST',
traditional : true,
data: $('form:first').serializeArray(),
// contentType: 'application/json; charset=utf-8', ---> this will give you Exeption Invalid JSON Primitive!!
success: function (result)
success(result)
,
error: function (result)
alert(result.responseText + "Error")
$('#divLoading').hide()
);
function success(result)
alert("success")
$('#divResult').html(result)
$('#divLoading').hide()
</script>
【讨论】:
【参考方案2】:根据我的说法,你可以实现的最好的就是这个,这肯定对你有用:
将您的 html 更改为: 首先把你上面的模型改成这个模型
@model List<CimenaCityProject.Models.MovieTheaters>
@
var selectlist = (SelectList)ViewBag.HomeCinemaID;
那么您的表单应该是这样的,我所做的更改是索引也提供给您的所有编辑器和下拉列表,这将为您提供每个字段的不同名称。请记住将您的列表绑定到您的下拉列表,因为我已经写了他们的“您的列表”:
@using (Html.BeginForm("Create", "Theatres", FormMethod.Post, new name = "TheatresForm", id = "TheatresForm" ))
@Html.ValidationSummary(true)
<table>
<tbody>
@for (int i = 0; i < maxNumberOfTheatres.Value; i++)
<tr>
<td id="NewTheaters">
@ViewBag.ErrorMassage
<div style="position:relative; top: 0px; left: 205px; width: 278px;">
@string.Format("Theares Number 0", i + 1)
</div>
<div>
<br />
<div class="form-group">
@Html.LabelFor(model => model[i].HomeCinemaID, "HomeCinemaID", new @class = "control-label col-md-2" )
<div class="col-md-10">
@Html.DropDownListFor(model => model[i].HomeCinemaID,selectlist)
@Html.ValidationMessageFor(model => model[i].HomeCinemaID)
</div>
<br />
</div>
<div class="form-group">
@Html.LabelFor(model => model[i].TheatersName, new @class = "control-label col-md-2" )
<div class="col-md-10">
@Html.EditorFor(model => model[i].TheatersName)
@Html.ValidationMessageFor(model => model[i].TheatersName)
</div>
<br />
</div>
<div class="form-group">
@Html.LabelFor(model => model[i].NumberHall, new @class = "control-label col-md-2" )
<div class="col-md-10">
@Html.EditorFor(model => model[i].NumberHall)
@Html.ValidationMessageFor(model => model[i].NumberHall)
</div>
<br />
</div>
<div class="form-group">
@Html.LabelFor(model => model[i].RowAmount, new @class = "control-label col-md-2" )
<div class="col-md-10">
@Html.EditorFor(model => model[i].RowAmount)
@Html.ValidationMessageFor(model => model[i].RowAmount)
</div>
</div>
</div>
</td>
</tr>
</tbody>
</table>
<div class="form-group">
<div class="col-lg-push-9">
<input type="button" name="Create" value="Create" id="Create" onclick="SaveTheatre()" />
</div>
</div>
<div id="divLoading" style="display: none; align-items: center">
<img src="~/Image/Elements/ajax-loader.gif" />
</div>
<div id="divResult"></div>
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts
@Scripts.Render("~/bundles/jqueryval")
现在您的脚本代码应该是这样的,只需在 jquery $('form:first').serializeArray();
中序列化整个表单即可:
function SaveTheatre()
$.ajax(
url: '@Url.Action("Create","Home")',
type: 'POST',
data: $('form:first').serializeArray(),
success: function(result)
success(result)
,
error: function(result)
alert(result.responseText + "Error") $('#divLoading').hide()
);
function success(result)
alert("success") $('#divResult').html(result) $('#divLoading').hide()
全部完成,您现在将在控制器中获取您的值:)
【讨论】:
编译器向我发送该错误:错误 1 找不到类型或命名空间名称“MovieTheaters”(您是否缺少 using 指令或程序集引用?) c:\Windows\Microsoft.NET\ Framework\v4.0.30319\Temporary ASP.NET Files\temp\6a3fbc73\2c7719c0\App_Web_54j5atfj.4.cs 31 CimenaCityProject 现已编辑,将您的模型线更新为@model List以上是关于使用 Ajax 将视图中的多个实例传递给控制器的主要内容,如果未能解决你的问题,请参考以下文章
将 knockoutjs 视图模型传递给多个 ajax 调用