简体   繁体   中英

Model is not updated with ajax post in asp.net mvc?

I am using asp.net mvc application. In my view page i have textbox like below code:

@Html.TextBoxFor(m => m.Id, new { @class = "form-control", @readonly = "readonly" })

Also, in form submit ajax post,

$('#btnSubmit').click(function(e)
    {
        $.ajax({
            url: '/button/Button',
            type: 'POST',
            data: {Id:1},
           });
    });

My controller:

 MasterM empcode = new MasterM();

        [HttpGet]
        public ActionResult Button()
        {

            var empcode = new MasterM();

            return View(empcode);
         }

        [HttpPost]
        public  ActionResult Button(MasterM model)
        {
            ModelState.Clear();
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            return View(model);
        }

after this form submit the value of the text box should change to new value (1). How can i achieve this in controller section itself. I know in ajax success we can manually update the element value but i want to achieve this in controller section and update model with new values.

When you are Posting your are sending only a Single Id and not the Entire Model , So basically this

public  ActionResult Button(MasterM model) will be empty 

and since you are returning back the empty set the text box will not be updated.

There are 2 things you can do here : 1) Modify the Receiving type to

 Public  ActionResult Button(int Id)
    {
    MasterM model = new MasterM();
    model.Id = Id;
     if (!ModelState.IsValid)
                {
                    return View(model);
                }
                return View(model);
    }

2) If you want to retain Model as your Param in Controller you need to serialize the Data in Jquery and post it .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM