Reputation: 242
I need to get the data from controller to the View as JSON format, but it doesn't work and i don't get it why.
My controller (i request it on the index action):
public class HomeController : Controller
{
CompanyTicketsDb _db = new CompanyTicketsDb();
public ActionResult Index()
{
var model =
_db.Tickets
.Select(r => new TicketListViewModel
{
Id = r.Id,
Name = r.Name,
Description = r.Description,
CompanyName = r.CompanyName,
Status = r.Status,
CompanyId = r.CompanyId,
});
if (Request.AcceptTypes.Contains("application/json"))
{
return Json(model, JsonRequestBehavior.AllowGet );
}
return View(model);
}
}
And my view (It is a partial view) looks liek that (Test mode):
@model IEnumerable<MvcApplication4.Models.TicketListViewModel>
<button id="Button1">asd</button>
@section scripts {
<script src="~/Scripts/knockout-3.2.0.js"></script>
<script>
$(document).ready(function () {
$("#Button1").click(function (evt) {
type: 'GET'
url = '/';
dataType = 'json';
contentType = 'application/json';
success = function (data) {
alert(data);
console.log("asd");
};
error = function () { alert("Error retrieving employee data!"); };
});
});
</script>
}
The thing is that i don't get any message (nor allert or console log) to test if returned JSON is valid so after that i could use them to fill View.
Upvotes: 0
Views: 90
Reputation: 5469
Because your syntax is wrong. You are using '=' but you should use ':'.
@model IEnumerable<MvcApplication4.Models.TicketListViewModel>
<button id="Button1">asd</button>
@section scripts {
<script src="~/Scripts/knockout-3.2.0.js"></script>
<script>
$(document).ready(function () {
$("#Button1").click(function (evt) {
$.ajax({
type: 'GET'
url : '/';
dataType : 'json';
contentType : 'application/json';
success : function (data) {
alert(data);
console.log("asd");
};
error : function () { alert("Error retrieving employee data!"); };
});
});
</script>
}
Upvotes: 7