ajax post back not working correctly

試著忘記壹切 提交于 2020-01-17 03:49:06

问题


Updated Question

Recently I need to implement a multi step wizard in ASP.NET MVC 3. After some research I was able to find this solution.

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

So I followed the example exactly as the have it except the minor changes listed below:

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>User</legend>
        <div class="wizard-step">
            @Html.Partial("UserInfo", this.Model)
        </div>
        <div class="wizard-step">
            @Html.Partial("Email", this.Model)
        </div>
        <div class="wizard-step">
            @Html.Partial("Cars", this.Model)
        </div>
        <p>
            <input type="button" id="back-step" name="back-step" value="< Back" />
            <input type="button" id="next-step" name="next-step" value="Next >" />
        </p>
    </fieldset>
}

As you can see I am using Partial View to render each steps.

Then I proceeded to create a ViewModel that would be used for this view:

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;
        }
    }

In the Cars Partial View I have the following code set up:

@model MVC2Wizard.Models.UserViewModel
<div class="editor-label">
    @Html.LabelFor(model => model.Model)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.Model)
    @Html.ValidationMessageFor(model => model.Model)
</div>
<div class="editor-label">
    @Html.LabelFor(model => model.Make)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.Make)
    @Html.ValidationMessageFor(model => model.Make)
</div>
<div>
    <p>
        <input id="addCar" type="submit" value="Add Car" />
    </p>
</div>
<script type="text/javascript">

    $("#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');
            }

        });
    }

</script>

Here is my WizardController that will get called when Action is performed.

        // 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;
        }

SO HERE IS MY PROBLEM: Everything works great except the model parameter in the AddCar HTTPPost is always null when the action is performed! How do I set up the code so that the User Inputs are passing in during the HTTPPost. Also I need to take "Car" info and add it into a collection. Buts that's step 2.


回答1:


Make sure you cancel the default action of the submit button by returning false from your callback:

$('#addExperience').click(function() {
    CallSomeAction();
    return false; // <!-- that's important to prevent the form being submitted normally
});

UPDATE:

After at last you have shown your code here's the problem:

[HttpPost]
public ActionResult AddCar(UserViewModel model)

The action parameter is called model. But you also have a property inside UserViewModel which is called Model which is conflicting. The default model binder doesn't know which one to bind.

So one possibility is to rename your action argument:

[HttpPost]
public ActionResult AddCar(UserViewModel uvm)

and on the client side:

data: JSON.stringify({ uvm: model })

UPDATE 2:

You have the following line in your javascript:

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

The problem is that your GET Index action in WizardController doesn't pass any view model to the view:

[HttpGet]
public ActionResult Index()
{
    return View();
}

So when you look at the generated source code of your page you will notice:

var model = null;

As a consequence you cannot expect to get anything other than null in your AddCar action.

This being said I suppose that you are not willing to send the view model to this action. You are willing to send the 2 values that the user entered in the form.

So you probably want something like this:

function AddCars() {
    $.ajax({
        url: '@Url.Action("AddCar")',
        type: 'POST',
        data: $('form').serialize(),
        success: function(result) {
            alert('successful');
        }
    });
}



回答2:


In your CallSomeAction do this.

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



回答3:


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

This line is not running when you clicking the submit button, but when the html page rendered. You can view the html source code to watch it.

Try this: (if your form has an id called 'thisform')

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


来源:https://stackoverflow.com/questions/8653120/ajax-post-back-not-working-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!