Reputation: 478
I'm new to ASP.NET Core, so I'm still trying to understand it.
I was trying to access an object from code behind. Is it possible? I have been trying and searching for hours and I have yet to understand it. I'll leave some of what I've tried bellow, which apparently isn't working. If I could get some insight on this I'd very much appreciate it.
In classic ASP.NET I always to the id approach from code behind to the client side. But now I've been asked to try a different approach. In this case, a loop. How can I do this? I've also been reading the microsoft documentation but I still can't understand this. I'd appreciate some help.
Here's a spinnet of what I tried:
// The controller
public class HomeController : Controller
{
public GetInfo GetInfo { get; set; }
public IActionResult Offers()
{
GetInfo = new GetInfo();
GetInfo.GetOffers();
return View();
}
}
// The GetInfo class which gets data from a JSON file
public class GetInfo
{
public Offer.RootObject Offers { get; set; }
public void GetOffers()
{
var client = new RestClient("whatever.com");
// client.Authenticator = new HttpBasicAuthenticator(username, password);
var request = new RestRequest("Home/GetOffersJson", Method.GET);
IRestResponse response = client.Execute(request);
var content = response.Content;
var obj = JsonConvert.DeserializeObject<Offer.RootObject>(content);
Offers = new Offer.RootObject
{
total = obj.total,
data = obj.data
};
}
}
// The View file, where I'm trying to access the object from c#, which supposedly is 'loaded'
@model HostBookingEngine_HHS.Models.GetInfo;
@{
ViewData["Title"] = "Offers";
}
@foreach (var item in Model.Offers.data)
{
<span asp-validation-for="@item.TextTitle"></span>
}
Thanks, in advance.
Upvotes: 0
Views: 1240
Reputation: 207
asp.net core view has four over loading these are
public virtual ViewResult View();
public virtual ViewResult View(string viewName, object model);
public virtual ViewResult View(object model);
public virtual ViewResult View(string viewName);
ASP.NET Core can use all of these with exact parameter You can pass your model object using Public Virtual ViewResult View(object model);
You need to pass your model object like this
return View(GetInfo);
which actually access your parameter object
@model HostBookingEngine_HHS.Models.GetInfo;
Also there are several method of passing data to view
Like ViewBag,ViewData which also grab the value in each request.
Upvotes: 2
Reputation: 822
To have Offers
available on view, you have to pass model to a view as an argument to View()
method. So in your case you have to make your action look like:
public IActionResult Offers()
{
GetInfo = new GetInfo();
GetInfo.GetOffers();
return View(GetInfo);
}
Upvotes: 1