带有ajax的MVC 3将复杂对象提交给控制器

时间:2013-06-24 17:43:15

标签: c# ajax asp.net-mvc-3 view controller

我正在使用mvc 3和c#以及ajax javascript,我有一个绑定了强类型模型的视图。

<%@ 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);            
    }

但是我不知道如何在控制器中创建Passenger词典数据之后如何保留它们。每次我点击Actionlink,乘客数据都为空......

如何在ajax呼叫之间保留乘客数据?

谢谢!

+++++++++++++++++++++++++++++++++++++++++++++++

编辑:

我正在使用下面给出的答案格式更新此问题...

View =

<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" />

Controller =

[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.
            }
        });
    });

1 个答案:

答案 0 :(得分:2)

通常的做法是在您的视图中添加表单。表单应该正确生成所有输入。鉴于模型:

public class Car
{
    public int Id { get; set; }
    public string Manufacturer { get; set; }
    public string Model { get; set; }
    public DateTime Year { get; set; }
    public List<Passanger> Passangers { get; set; }
}

public class Passanger
{
    public int Id { get; set; }
    public string Name { get; set; }
}

该视图应具有以下内容:

@model Car
@using(Html.BeginForm("actionName", "controllerName", FormMethod.Post, new { id = "my-form" }))
{
    @Html.HiddenFor(x => x.Id)
    @Html.TextBoxFor(x => x.Manufacturer)
    @Html.TextBoxFor(x => x.Model)
    @Html.TextBoxFor(x => x.Year)

    for(int i = 0, i < Model.Passangers.Count(), i++)
    {
        @Html.HiddenFor(x => Model.Passangers[i].Id)
        @Html.HiddenFor(x => Model.Passangers[i].Name)
    }

    <input type="button" value="Submit" id="form-submit" />
}

<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.
            }
        });
    });
</script>

这样,当您的表单发布时,发布的数据将包括乘客,因为他们的信息是在视图中的隐藏处呈现的。