Sasi Dhivya
Sasi Dhivya

Reputation: 501

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.

Upvotes: 0

Views: 2207

Answers (1)

REDEVI_
REDEVI_

Reputation: 684

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 .

Upvotes: 1

Related Questions