我只使用带有 c# 和 ajax javascript 的 mvc 3,并且我有一个绑定了强类型模型的视图。
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcApplication2.Models.Car>" %>
我正在通过 ActionLink 提交...
<%=Html.ActionLink("Add Car", "AddCar", "Car", new { id = "tester" })%>
这一切都通过 ajax/javascript 调用...
$('#tester').click(function (e)
{
e.preventDefault();
$(this).parents('form').first().submit();
$.ajax({
url: "Car/AddCar",
type: "POST",
data: { ID: $('#carid').val(), Manufacturer: "test", Model: "Test", Year: "01/01/2010" },
success: function (data)
{
alert(data);
}
});
});
控制器方法获取页面数据就好了......
[HttpPost]
public ActionResult AddCar(Car newcar)
{
if (newcar.Passengers == null)//this is always null... data is not being persisted
newcar.Passengers = new Dictionary<int, string>();
newcar.Passengers.Add(newcar.ID, newcar.Model);
IList<Car> cars = _carService.AddCarToGarage(newcar);
return View("Index", newcar);
}
但是,我不知道如何在控制器中创建乘客字典数据后保留它。每次我点击 Actionlink 时,Passengers 数据都是空的……
如何在 ajax 调用之间保留乘客数据?
谢谢!
+++++++++++++++++++++++++++++++++++++++++++++++++++
编辑:
我正在用下面对我有用的答案格式更新这个问题......
视图 =
<form id="my-form" method="post" action="/Car/AddCar">
<h2>Index</h2>
<%
Response.Write("<input type=\"hidden\" name=\"ID\" value=\"" + Model.ID + "\">");
Response.Write("<input type=\"hidden\" name=\"Manufacturer\" value=\"" + Model.Manufacturer + "\">");
Response.Write("<input type=\"hidden\" name=\"Model\" value=\"" + Model.Model + "\">");
Response.Write("<input type=\"hidden\" name=\"Year\" value=\"" + Model.Year.ToShortDateString() + "\">");
if (Model.Passengers != null)
{
for (int i = 0; i < Model.Passengers.Count; i++)
{
Response.Write("<input type=\"hidden\" name=\"newcar.Passengers[" + i + "].Id\" value=\"" + Model.Passengers[i].Id + "\">");
Response.Write("<input type=\"hidden\" name=\"newcar.Passengers[" + i + "].Name\" value=\"" + Model.Passengers[i].Name + "\">");
}
}
%>
<input type="button" value="Submit" id="form-submit" />
控制器 =
[HttpPost]
public ActionResult AddCar(Car newcar)
{
if (newcar.Passengers == null)
newcar.Passengers = new List<Passenger>();
Passenger p = new Passenger();
p.Id = newcar.ID;
p.Name = "tester";
newcar.Passengers.Add(p);
return View("Index", newcar);
}
javascript =
<script type="text/javascript">
$(document).on('click', '#form-submit', function () {
$.ajax({
url: "Car/AddCar",
type: "POST",
data: $('form#my-form').serialize(),
success: function (data) {
alert(data);
// put the data in the container where you have the form.
}
});
});