3
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;
}
I want it now in a view Razor call this method and put the result into a javascript variable. How can I do this?
Update:
I’m now trying to do with json, but I’m not getting it. Look what I have on view:
$.ajax({
url: '/Home/SpotNR',
type: 'POST',
success: function (result) {
topSpot = result.Data;
}
});
and in the 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 I don’t understand why it doesn’t work, but he never goes to success
(topSpot remains Undefined) but the answer on Chromedevtools is like this:
{"ContentEncoding":null,"ContentType":null,"Data":{"Spot":3},"JsonRequestBehavior":1,"MaxJsonLength":null,"RecursionLimit":null}
The number of spot is correct, so he processed the method well.
In Success do:
topSpot = result.Data.Spot;
– Jéf Bueno
It does not reach the Success, goes to error instead...which may be wrong?
– ihavenokia
Asks for error parameters (are 3, I think) and printa on the screen to see.
– Jéf Bueno
parse error and no Conversion from text to application/json
– ihavenokia
Puts
dataType: 'json'
in ajax and forehead– Jéf Bueno
Thanks for the help @jbueno ! So back to Success no problem. I’ll see the differences from
application/json
forjson
.– ihavenokia
Great then. If you want, you can see something at this link
– Jéf Bueno