I have this method in a controller :
int GetSpot()
{
List<CompanyDetail> topCompanies = GetTopCompanies();
CompanyDetail topCompany1 = topCompanies.Where(x => x.Company.TopCompany == 1).FirstOrDefault();
if (topCompany1 == null) return 1;
CompanyDetail topCompany2 = topCompanies.Where(x => x.Company.TopCompany == 2).FirstOrDefault();
if (topCompany1 == null) return 2;
CompanyDetail topCompany3 = topCompanies.Where(x => x.Company.TopCompany == 3).FirstOrDefault();
if (topCompany1 == null) return 3;
return -1;
}
Now I want a view Razor to call this method and put the result in a javascript variable. How can I do this?
Update:
I'm now trying to do json, but I can not. Look what I have in view :
$.ajax({
url: '/Home/SpotNR',
type: 'POST',
success: function (result) {
topSpot = result.Data;
}
});
and no controller:
public JsonResult SpotNR()
{
int spot = -1;
IList<CompanyDetail> topCompanies = PresentationServices.Helper.GetCompaniesAll();
CompanyDetail topCompany1 = topCompanies.Where(x => x.Company.TopCompany == 1).FirstOrDefault();
if (topCompany1 == null) spot = 1;
CompanyDetail topCompany2 = topCompanies.Where(x => x.Company.TopCompany == 2).FirstOrDefault();
if (topCompany1 == null) spot = 2;
CompanyDetail topCompany3 = topCompanies.Where(x => x.Company.TopCompany == 3).FirstOrDefault();
if (topCompany1 == null) spot = 3;
JsonResult returnObj = new JsonResult
{
Data = new
{
Spot = spot
}
};
return Json(returnObj);
}
The problem is that I do not understand why it does not work, but it never goes to success
(topSpot remains undefined) but the answer in ChromeDevTools looks like this:
{"ContentEncoding":null,"ContentType":null,"Data":{"Spot":3},"JsonRequestBehavior":1,"MaxJsonLength":null,"RecursionLimit":null}
The spot number is correct, so it processed the method well.