Reputation: 126
I have a class like below:
public class CustomBenefitCommittee
{
public bool? IsChecked { get; set; }
public bool PropertyError { get; set; }
}
And I am using this class as a list type in MVC model like:
@model List<CustomBenefitCommittee>
I want to retrieve data from this model in jQuery. I am trying right now as
@{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var json = serializer.Serialize(Model);
}
var model = @Html.Raw(json);
if(model != null && @Html.Raw(json) != "undefined")
{
$.each(model, function () {
alert(model.PropertyError );
});
}
This is giving me undefind. Can someone help me out getting the values from this model.
Upvotes: 0
Views: 3323
Reputation: 86
Make an method in you controller that returns model list (in json format) like:
public JsonResult LoadList()
{
var modelList=new List<CustomBenefitCommittee>();
modelList= //get your list of model
var jsonResult = Json(modelList, JsonRequestBehavior.AllowGet);
return jsonResult;
}
Now on View call this method throught jquery like:
<script>
$(document).ready(function() {
$.getJSON('/"Controller Name"/"Action Name as "LoadList', function (data) {
if (data.length == 0) {
alert('No data');
}
else{
$(data).each(function() {
alert(this.PropertyError);
});
}
});
});
</script>
Upvotes: 1
Reputation: 41
From Server Side: First you need to add actions in the controller returns JsonResult.
public JsonResult GetData(int id)
{
var data = new
{
id,
age = 23
}
return Json(data,JsonRequestBehavior.AllowGet);
}
From Client Side: you need ajax call to retrieve the data
function getData(id){
var data = {id: id};
$.get('/Home/GetData/', data,
function (response) {
alert(JSON.stringify(response));
},'json'
};
}
OR if you are sending data to model and you want to use it in your javascript or jquery code you can use NewtonSoft.Json.
First install the Package in your solution:
PM> install-package NewtoSoft.Json
Second you can make your view like this:
@model ...
@using Newtonsoft.Json
<script type="text/javascript">
var data = @Html.Raw(JsonConvert.SerializeObject(this.Model));
</script>
than you can use this data like this:
$.each(model, function(index, item) { alert(item.PropertyError); });
And also you can use one the javascript frameworks like Konockout.js or angularjs
Upvotes: 0
Reputation: 1796
Make a loop like this:
$.each(model, function(key, value) { alert(value.PropertyError); });
It will work.
Upvotes: 1