3
Answers

MVC-Pass Model data from View to Controller using Ajax

Photo of Pravin Ghadge

Pravin Ghadge

7y
234
1
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)

3
Photo of Gaurav Raut
NA 171 2 7y
function Show() {
var data = $('#CNform').serialize();
console.log(data);
$.ajax({
type: 'POST',
cache: false,
url: '/CN/Show',
data: data,
success: function (data, textStatus, jqXHR) {
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
}
 
 
And change the type of parameter
//Controller
[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
public string Show(CNModel modelParameter)
{
// Code
}
Accepted
1
Photo of Faizan Syed
NA 16 1 7y
Thanks @Gaurav Raut
1
Photo of Pravin Ghadge
NA 2.5k 358.5k 7y
Thanx a lot Gaurav.
 
Issue has been resolved .
 
Also one thing i have modified in the cshtml file is:
 
  1. @using (Html.BeginForm(nullnullnew { @id = string.Empty }, FormMethod.Post,  
  2. new { @id = "CNform" })