我只用MVC 3與C#和Ajax JavaScript和我有綁定了一個強類型的模型的視圖。MVC 3使用Ajax提交複雜對象控制器
<%@ 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的,乘客數據爲空...
如何保持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.
}
});
});
該視圖必須同時擁有乘客,並且您必須在ajax中發送數據,並從窗體調用乘客數據,否則每次都將爲空! – Fals
如何通過數據參數發送字典? 我是否需要從視圖中的模型創建現有字典值的.js變量,然後傳入數據參數數組? –
RenleyRenfield
你爲什麼要同時提交表單並執行ajax請求? – rossipedia