Skip to content
Loading
Passing value from MVC View to Controller using ajax  
  •             "@Model.Id" class="form-group">  
  •                 "button" class="btn btn-primary" value="Save" id="btnEdit"/>  
  •               
  •           
    1. @section Scripts {  
    2.     @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}  
    3.   
    4.     "text/javascript">  
    5.         $(document).ready(function () {  
    6.             $('#btnEdit').click(function () {  
    7.                 var id = $(this).parent()[0].id;  
    8.                 var consultView = {  
    9.                     Id: id,  
    10.                     DepartmentId: $('#DepartmentId').val(),  
    11.                     Date: $('#Date').val(),  
    12.                     Description: $('#Description').val()  
    13.                 };  
    14.   
    15.                 $.ajax({  
    16.                     type: 'POST',  
    17.                     url: "@Url.Action("Edit")",  
    18.                     contentType: "application/json; charset=utf-8",  
    19.                     dataType: 'json',  
    20.                     data: JSON.stringify({consultView: consultView}),   
    21.                     success: function (data) {  
    22.                         alert(data.message);  
    23.                     },  
    24.                     error: function (ex) {  
    25.                         alert('Error.' + ex);  
    26.                     }  
    27.                 });  
    28.             });  
    29.         });  
    30.       
    31. }  
    1.         [HttpPost]  
    2.         //[ValidateAntiForgeryToken]  
    3.         public async Task Edit(ConsultViewModel consultView)  
    4.         {  
    5.             if (ModelState.IsValid)  
    6.             {  
    7.                 //More code..  
    8.   
    9.                 return Json(new { success = true, message = "Done." });                 
    10.             }  
    11.   
    12.             return View(consultaView);  
    13.         }  
     Thanks!

    3 Replies

    Know the answer? Post it — somebody with the same question will find it here.