简体   繁体   中英

How to send form data to controller to make an ajax request for saving data in Db

I am working on a ASP.net MVC 2.0 application.

I have a form , after entering data into it, the user clicks on submit.

Here, i dont want to do the enitre post back rather i just want to make an ajax request to send the form data to the corresponding controller method and insert and send the response to same page.

Since, i am using MVC 2.0, i can not use AJax.beginForm. i need to rely on jquery Ajax methods.

Please help on this.

I am using a strongly typed view.

You can directly post your data using serialize method of JavaScript.

In view

  @model ViewModel

   @using (Html.BeginForm("Save", "Home", FormMethod.Post, new { id = "FormId" }))
            {

                <input type="button" value="Save" onclick="SaveDemo();" />

             }

java script save function

   function SaveDemo() {
   $.ajax({
            url: '',
            type: 'POST',
            cache: false,
            data: jQuery("#FormId").serialize(),
            success: function (result) {
             // do accordingly as per your result                 
         } }); }

and controller save method will like :

[HttpPost]
public ActionResult Save(ViewModel viewModel)
    {
      if (this.ModelState.IsValid)
        {
          // save to DB
        }

       return this.View(viewModel);
    }

You can subscribe to a form's submit event and send data via ajax:

$('form').submit(function(){
    var $form = $(this);
    if($form.valid()) {
        var action = $form.prop('action'),
            method = $form.prop('method'),
            data = $form.serialize();

        $.ajax({
            url: action,
            type: method,
            data: data,
            success: function (response) {
                // success function
            }
        });
    }
    return false; // do not forget to return false to prevent the default behaviour
});

Update:

Controller:

[HttpPost]
public ActionResult Save(YourViewModel viewModel)
{
    if (ModelState.IsValid)
    {
        // Save to db
    }
    return PartialView("_PartialViewName", viewModel);
}

Try this,

In below code i initialize model and post that model.

var returnValue = new Object();//dynamically fill model value with different model entity
            returnValue.vendorSiteSustainabilityList = VendorSiteSustainability;
            returnValue.VendorSiteId = '@Model.VendorSiteId';
            returnValue.ServiceTypeId = '@Model.ServiceTypeId';
            returnValue.HaulerName = $("#HaulerName").val();
            returnValue.FacilityName = $("#FacilityName").val();
            returnValue.CityId = parseInt($("#CityId").val());
            returnValue.StateId = parseInt($("#StateId").val());
            returnValue.CoutryID = parseInt($("#CoutryID").val());

            var request = $.ajax({
                url: '',
                type: 'POST',
                cache: false,
                data: JSON.stringify(returnValue),
                dataType: 'json',
                contentType: 'application/json; charset=utf-8'
            });

            request.done(function (msg) {

                if (msg != null && msg.IsValid != null) {

                    if (msg.IsValid == true) {
                        //write code when your data successfully operated
                    }
                }
            });

Model declaration:

[Serializable]
    public class myModel
    {}

Controller:

[HttpPost]
        public ActionResult SaveAction(myModel model)
        {
            if (model != null && ModelState.IsValid)
            {

            }
            return Json(new { IsValid = ModelState.IsValid });
        }

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