How to send a model in jQuery $.ajax() post request to MVC controller method

前端 未结 7 1787
南方客
南方客 2020-11-27 02:47

In doing an auto-refresh using the following code, I assumed that when I do a post, the model will automatically sent to the controller:

$.ajax({
    url: \'         


        
相关标签:
7条回答
  • 2020-11-27 03:20

    This can be done by building a javascript object to match your mvc model. The names of the javascript properties have to match exactly to the mvc model or else the autobind won't happen on the post. Once you have your model on the server side you can then manipulate it and store the data to the database.

    I am achieving this either by a double click event on a grid row or click event on a button of some sort.

    @model TestProject.Models.TestModel
    
    <script>
    
    function testButton_Click(){
      var javaModel ={
      ModelId: '@Model.TestId',
      CreatedDate: '@Model.CreatedDate.ToShortDateString()',
      TestDescription: '@Model.TestDescription',
      //Here I am using a Kendo editor and I want to bind the text value to my javascript
      //object. This may be different for you depending on what controls you use.
      TestStatus: ($('#StatusTextBox'))[0].value, 
      TestType: '@Model.TestType'
      }
    
      //Now I did for some reason have some trouble passing the ENUM id of a Kendo ComboBox 
        //selected value. This puzzled me due to the conversion to Json object in the Ajax call. 
      //By parsing the Type to an int this worked.
    
      javaModel.TestType = parseInt(javaModel.TestType);
    
      $.ajax({
          //This is where you want to post to.
          url:'@Url.Action("TestModelUpdate","TestController")', 
          async:true,
          type:"POST",
          contentType: 'application/json',
          dataType:"json",
          data: JSON.stringify(javaModel)
      });
    }
    </script>
    
    
    //This is your controller action on the server, and it will autobind your values 
    //to the newTestModel on post.
    
    [HttpPost]
    public ActionResult TestModelUpdate(TestModel newTestModel)
    {
     TestModel.UpdateTestModel(newTestModel);
     return //do some return action;
    }
    
    0 讨论(0)
提交回复
热议问题