ajax回发不正常

更新的问题

最近我需要在ASP.NET MVC 3中实现一个多步骤向导。经过一些研究,我能够找到这个解决方案。

http://afana.me/post/create-wizard-in-aspnet-mvc-3.aspx

所以除了下面列出的小改动之外,我完全按照它的例子进行操作:

@using (Html.BeginForm()) { @Html.ValidationSummary(true) 
User
@Html.Partial("UserInfo", this.Model)
@Html.Partial("Email", this.Model)
@Html.Partial("Cars", this.Model)

<input type="button" id="back-step" name="back-step" value=" " />

}

如您所见,我正在使用部分视图来呈现每个步骤。

然后我继续创建一个将用于此视图的ViewModel:

 public class UserViewModel { public UserViewModel() { } [Required(ErrorMessage="Username")] public string UserName { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public string Make { get; set; } public string Model { get; set; } } 

在汽车部分视图中,我设置了以下代码:

 @model MVC2Wizard.Models.UserViewModel 
@Html.LabelFor(model => model.Model)
@Html.EditorFor(model => model.Model) @Html.ValidationMessageFor(model => model.Model)
@Html.LabelFor(model => model.Make)
@Html.EditorFor(model => model.Make) @Html.ValidationMessageFor(model => model.Make)

$("#addCar").click(function () { AddCars(); return false; }); function AddCars() { var model = @Html.Raw(Json.Encode(Model)); $.ajax({ url: '@Url.Action("AddCar")', type: 'POST', contentType: 'application/json; charset=utf-8', data: JSON.stringify({model: model}), success:function(result) { alert('successful'); } }); }

这是我的WizardController,它将在执行Action时被调用。

  // GET: /Wizard/ [HttpGet] public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(UserViewModel Person) { if (ModelState.IsValid) return View("Complete", Person); return View(); } [HttpPost] public ActionResult AddCar(UserViewModel model) { return null; } 

这就是我的问题:除了执行操作时AddCar HTTPPost中的模型参数始终为null,一切都很有效! 如何设置代码以便在HTTPPost期间传入用户输入。 另外,我需要获取“Car”信息并将其添加到集合中。 但那是第2步。

确保通过从回调中返回false来取消提交按钮的默认操作:

 $('#addExperience').click(function() { CallSomeAction(); return false; // 

在CallSomeAction中执行此操作。

  var datatoPost = $('form').serialize(); $.ajax({ url: '@Url.Action("SomeAction")', type: 'POST', data: datatoPost, dataType: 'json', success: function(result) { } }); 

var model = @ Html.Raw(Json.Encode(Model));

单击提交按钮时,此行未运行,但是在呈现html页面时。 您可以查看html源代码来观看它。

试试这个:(如果你的表单有一个名为’thisform’的id)

 function CallSomeAction() { var model = {}; $('#thisform').find("input[checked], input[type='text'], input[type='hidden'], input[type='password'], input[type='submit'], option[selected], textarea") .filter(":enabled") .each(function() { params[this.name || this.id || this.parentNode.name || this.parentNode.id] = this.value; }); $.ajax({ url: '@Url.Action("SomeAction")', type: 'POST', data: model, success: function (result) { // TODO: process the result from the server } });}