Pravin Ghadge

Pravin Ghadge

  • 544
  • 2.1k
  • 580.1k

MVC-Pass Model data from View to Controller using Ajax

Dec 6 2017 12:54 AM
Hi All,
 
I want to pass the model from view to controller using Ajax
But I am getting null paramter value. Iam not able to understand where iam wrong.
  1. //Model Class  
  2. public class CNModel  
  3. {  
  4. public CNModel()  
  5. {  
  6. }  
  7. public string ID { getset; }  
  8. public string Name { getset; }  
  9. }  
  10. //csHTML  
  11. @model CN_MVC.Models.CNModel  
  12. @using Newtonsoft.Json  
  13. @using (Html.BeginForm(new { @id = "CNform" }))  
  14. {  
  15. <label>ID</label>  
  16. @Html.TextBoxFor(m => m.ID, new { @class = "form-control", id = "txtID", placeholder = "Enter ID"})  
  17. <label>Name</label>  
  18. @Html.TextBoxFor(m => m.Name new { @class = "form-control", id = "txtName", placeholder = "Enter Name"})  
  19. <input type="button" id="btnShow" class="btn" value="Pass To Controller" onclick="Show()" />  
  20. }  
  21. <script type="text/javascript">  
  22. function Show() {  
  23. debugger;  
  24. //var data = @Html.Raw(JsonConvert.SerializeObject(Model));  
  25. var data = '@Html.Raw(Json.Encode(Model))';  
  26. $.ajax({  
  27. type: 'POST',  
  28. // dataType: 'html', // this can be omitted - the ajax() function will work it out  
  29. cache: false,  
  30. url: '/CN/Show',  
  31. data: data,  
  32. success: function (data, textStatus, jqXHR) {  
  33. },  
  34. error: function (jqXHR, textStatus, errorThrown) {  
  35. }  
  36. });  
  37. }  
  38. </script>  
  39. //Controller  
  40. [HttpPost]  
  41. [AcceptVerbs(HttpVerbs.Post)]  
  42. public string Show(string modelParameter)  
  43. {  
  44. var DeserializedModel = JsonConvert.DeserializeObject<RCNModel>(modelParameter);  
  45. }  

Answers (3)