Pass the return (integer) of a method from Controller to View

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;
}

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.

    
asked by anonymous 08.02.2017 / 19:28

1 answer

3

Views do not call actions, at least not directly. It seems to me that you are trying to summarize a desktop application behavior for a web application.

What you can do is a pro server request and return a JSON with the value returned from your function.

Example:

No Controller:

public JsonResult GetSpot()
{
    int result = -1; //seu código deve setar o valor de result
    return Json(new { data = result }, JsonRequestBehavior.AllowGet);
}

In View :

$.ajax({
    url: '@Url.Action("GetSpot", "Controller")',
    data: data,
    type: 'GET',
    dataType: 'json',
    success: function(response){
        var variavel = response.data; //Aqui está o retorno do controller
    },
    error: function(){
        // Algo deu errado
    }
});
    
08.02.2017 / 19:43