I would like to do "Add Service Reference" in .NET Standard project.(Visual Studio 2017)

I installed "System.ServiceModel.Http" and "System.ServiceModel.Security" on NuGet in order to make WCF access possible.

However, there is no "Add Service Reference" menu item in the .NET Standard project. How do I add a service reference?

It exists in the .NET Framework project but it does not exist in the .NET Standard project, so it is in trouble.

I have problem in Application_BeginRequest will execute twice when network disconnect and then reconnecting in Global.asax?

 protected void Application_BeginRequest()
        {
            if (HttpContext.Current.Items["db"] == null)
            {
                HttpContext.Current.Items["pdb"] = NewDb();
            }
        }

I have a function and it takes 3 to 5mins to execution if clients network will disconnected between execution what will happen?

public JsonResult SaveDetails(int id)
{
  // 100 lines executed 
  // users network will disconnected,
  // 150 lines to be executed. what will happen it executes or not?And Application_BeginRequest will execute again?
}

My problem in database transaction that is my all code is in transaction but sometimes remaining 150 lines only effects in database.

I have created an angular application, using command ng new my-application. I want to migrate that application to Asp.Net application. How to transform my application to Asp.net application with MVC.

I have a rad editor where i need to add font size drop down which has values like 11px, 12px etc. How do I achieve this in aspx page?

i want send mail (text and document) using mailchimp in asp.net c# for this. I download dll file (v3.0 API) from nuget and generate key and Id form mailchimp website.I Also Add API key in webconfig file now i can't implement code for send mail using mailchimp in cs page in asp.net c#..

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MailChimp.Net;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
   MailChimpManager manager = new MailChimpManager("string for API Key");



}
}

Have two sites on IIS 7.5 server Each site has the same error page, one operating and one inoperative. Both have similar web.config structures and there are no significant differences in server settings.Both pipelines are equally integrated with the same integration. i was googling and do something like ↓, but it was useless. How can we solve it? The code below shows the same settings for the web.config files on both sites.

<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules>
  <add type="te.test, Version=1.1.1.0" name="testModule" />
</modules>
<httpErrors errorMode="Custom">
        <error statusCode="404" prefixLanguageFilePath="" path="/error_page/error_test.html" responseMode="ExecuteURL" />
        <error statusCode="500" prefixLanguageFilePath="" path="/error_page/error_test.html" responseMode="ExecuteURL" />
</httpErrors>
</system.webServer>

<system.web>
<customErrors defaultRedirect="http://test.test/error_page/error_test.html" mode="On">
</customErrors>
</system.web>

I have an archive filled with files of different types, pictures, pdf etc, stored as byte arrays.

What would be the proper way to serve these files to a client? Is there any difference if that client is a browser, another web app, curl or something else?

As you may have noticed I am not familiar with serving files. Other than static files to a web page.

Any help is appreciated.

I created a Core 2.0 project with User Base Authentication, but upon looking at the default AccountController only the Logout() action method was generated.

Where are the other scaffold items like Register(), ForgotPassword(), ExternalLogin(), etc...

However, I can register users just fine.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Core2.Data;

namespace Core2.Controllers
{

  [Route("[controller]/[action]")]
  public class AccountController : Controller
  {
     private readonly SignInManager<ApplicationUser> _signInManager;
     private readonly ILogger _logger;

     public AccountController(SignInManager<ApplicationUser> signInManager, ILogger<AccountController> logger)
     {
        _signInManager = signInManager;
        _logger = logger;
     }

     [HttpPost]
     [ValidateAntiForgeryToken]
     public async Task<IActionResult> Logout()
     {
        await _signInManager.SignOutAsync();
        _logger.LogInformation("User logged out.");
        return RedirectToPage("/Index");
     }
  }
}

I have 3 drop down lists, and I need to select data from these dropdown lists and display results on text boxes instead of a Grid. On selectedIndexChange of the last drop down I would like to populate the data on text boxes. e.g display minimum and maximum on text boxes.

In a self hosted webapi console application project, I am not able to hit the SayHello method using http://localhost:9998/api/shri/flows/config.

Error:

{
    "Message": "No HTTP resource was found that matches the request URI 'http://localhost:9998/api/shri/flows/config'.",
    "MessageDetail": "No route data was found for this request."
}

Controller:

    class ConfigController : ApiController
    {
        [HttpGet, Route("{id}/flows/config")]
        public string SayHello([FromUri] string id)
        {
            return "Hello " + id;
        }
    }

Startup:

    public class Startup
    {
        // This code configures Web API. The Startup class is specified as a type
        // parameter in the WebApp.Start method.
        public void Configuration(IAppBuilder appBuilder)
        {
            // Configure Web API for self-host. 
            HttpConfiguration config = new HttpConfiguration();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            appBuilder.UseWebApi(config);
        }
    }

To keep the self hosted webapi running I have the following:

    public class Program
    {
        static void Main()
        {
            Uri myUri = new Uri(@"http://localhost:9998/");
            // Let have our configurations readY
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(myUri);

            // configure routes
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            HttpSelfHostServer server = new HttpSelfHostServer(config);

            // Start listening 
            server.OpenAsync().Wait();

            Console.WriteLine("WebApi hosted on " + myUri.AbsoluteUri + " It can be tested now");
            Console.ReadLine();

        }
    }

What am I missing?

i have one call back function in my model. i.e void method. how to pass that result to view.

my problem is while uploading file to amazon s3, it's returning progress value. i need to get that value in view.

my code as follows

public bool sendMyFileToS3(EmployeeModel e, string bucketName, string subDirectoryInBucket)
        {
            IAmazonS3 client = new AmazonS3Client(RegionEndpoint.USEast2);
            TransferUtility utility = new TransferUtility(client);
            TransferUtilityUploadRequest request = new TransferUtilityUploadRequest();

            if (subDirectoryInBucket == "" || subDirectoryInBucket == null)
            {
                request.BucketName = bucketName; //no subdirectory just bucket name  
            }
            else
            {   // subdirectory and bucket name  
                request.BucketName = bucketName + @"/" + subDirectoryInBucket;
            }
            try
            {
                request.Key = RandomString() + Path.GetExtension(e.File.FileName); //file name up in S3  
                request.InputStream = e.File.InputStream;
                request.CannedACL = S3CannedACL.PublicRead;
                request.UploadProgressEvent += new EventHandler<UploadProgressArgs>(UploadFile_ProgressBar); //call bcak function
                utility.Upload(request);
            }
            catch(AmazonS3Exception)
            {
                throw;
            }
             //commensing the transfer  

            //Generate link with expiry date.
            Amazon.S3.Model.GetPreSignedUrlRequest aa = new Amazon.S3.Model.GetPreSignedUrlRequest();
            aa.BucketName = request.BucketName;
            aa.Key = request.Key;
            aa.Expires = new DateTime().AddDays(2);
            string url = client.GetPreSignedURL(aa);
            url = url.Remove(url.IndexOf('?'));
            return true;  
        }
        public void UploadFile_ProgressBar(object sender, UploadProgressArgs e)
        {
            int pctProgress = (int)(e.TransferredBytes * 100 / e.TotalBytes);
        }

every second "pctProgress" this parameter is replacing with new value. when ever replacing with new value it should pass to view. how to do this. please any suggestions.

I try to make an ASP.NET project for my school and i have a problem.

I've added this:

services.AddAuthentication().AddGoogle(googleOptions =>
{
    googleOptions.ClientId = Configuration["Authentication:Google:ClientId"];
    googleOptions.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
});

Wich allow me to do an OAuth with G+ API (and i works fine), but after that i want to be able to use Gmail API to have push notifications when the user received a mail.

I don't know how to do, and if it's possible, i read a lot of things but no one with this method...

Thank you in advance.

I need to programmatically update a row in my GridView when user clicks Update. I have the ordinary Update working, but I need to have various validations in place. I already have a function which does this and I would like to simply reuse this function when Update is clicked. The problem is that updating requires an Update Command, and the Update Command does not have the validations in place. So basically what I want to be able to do is bypass the Update Command so that I can just use the function I already have. Is this possible?

protected void update_Click(object sender, GridViewUpdateEventArgs e)
{
    myDataSource.UpdateCommand = "UPDATE [xyz] SET [s] = @s, [t] = @t, [c] = @c, [l] = @l, [p] = @p, [d] = @d, [k] = @k WHERE [Id] = @Id";

    lbStatusLabel2.Text= checkDuplicate(GridView1.Rows[e.RowIndex].Cells[3].Text, GridView1.Rows[e.RowIndex].Cells[4].Text, GridView1.Rows[e.RowIndex].Cells[5].Text, GridView1.Rows[e.RowIndex].Cells[6].Text, GridView1.Rows[e.RowIndex].Cells[7].Text, GridView1.Rows[e.RowIndex].Cells[8].Text, GridView1.Rows[e.RowIndex].Cells[9].Text, "45");
}

I have looked at like twenty answers on here regrading this and none of them seem to be working for me. They all seem hackish as well.

I have this huge View model that I am trying to pass back and forth between two PartialViewResults via Ajax. However, nothing seems to work.

Here is a "generic" version of my code:

Controller

public PartialViewResult _View1(Model model)
{
  return PatialView(model);
}

*I have another one of these for Partial view2*

View

<div id="div1">Load View 1 here</div>

<script>
var m = @Html.Raw(Json.Encode(Model));
    console.log(m);
    $.ajax({
        url: '@Url.Action("_View1")',
        data: {'model' : m},
        dataType: "html",
        success: function (result) {
            $("#View1").html(result);
        },
        error: function (e) {
            $("#View1").html("<div class='alert alert-danger' role='alert'>Error: Getting View.</div>");
        }
    });
</script>

I have tried various configurations on my ajax calls. Any help would be awesome thank you. I do not want to have to store each variable of the view model into vars and pass them individually to the controller. The view model is way too big for this.

*Note: When i do a console.log(m) the console of my browser shows me all of my view data. I am just unsure how to pass all of that data to the controller

Note2: If there is a solution that is on stackoverflow already, please feel free to link to it. For some reason i wasn't able to find it.*

I have an ASP.NET MVC project that uses Razor for rendering HTML using the built-in engine.

I would like to create Email Templates using the same process. Usually, these templates are created as part of a Action Context (for instance, when a user has completed a purchase, a notification would be sent). However, there are some instances where there is no context available. For instance, sending a log when the application is restarting.

This is what I have come up with so far:

public static string RenderRazor(ViewTemplateType TemplateType, string ViewName, PageController Controller = null, object Model = null)
{
    try
    {
        ControllerContext Context;

        if (Controller != null)
        {
            Context = Controller.ControllerContext;
        }
        else
        {
            if (HttpContext.Current == null)
            {
                throw new InvalidOperationException("Cannot render a razor template if the current context is null (See DEV-1669).");
            }
            var RouteData = new RouteData();
            RouteData.Values.Add("controller", "Pseudo");
            Controller = new PseudoController(Model);
            Context = new ControllerContext(new HttpContextWrapper(HttpContext.Current), RouteData, Controller);
            // If this isn't set, an error occurs when calling FindView/FindViewPartial.
            Controller.ControllerContext = Context;
        }

        // I'm not really sure what the point of this is...
        // Further, it was actually causing an exception to occur since the Controller may not actually be populated?
        // Without this, the Notification Debug wasn't working - so apparently it is required in some circumstances for notifications.
        if (Controller != null && Controller.ViewData != null && Model != null) { Controller.ViewData.Model = Model; }

        var ViewResult = ViewName.StartsWith("_")
            ? ViewEngines.Engines.FindPartialView(Context, string.Format("~/Views/Template/{0}/{1}.cshtml", TemplateType, ViewName))
            : ViewEngines.Engines.FindView(Context, string.Format("~/Views/Template/{0}/{1}.cshtml", TemplateType, ViewName), string.Format("~/Views/Template/{0}/_Shared/{1}.cshtml", TemplateType, "_Layout"));

        if (ViewResult.View == null)
        {
            StringBuilder LocationBuilder = new StringBuilder();
            string[] SearchedLocations = ViewResult.SearchedLocations.ToArray();
            for (int i = 0; i < SearchedLocations.Length; i++)
            {
                LocationBuilder.Append(string.Format("({0}) {1} ", i, SearchedLocations[i]));
            }

            throw new InvalidOperationException(string.Format("Could not find the {0} Template named {1} using the {2} Master. Locations Searched: {3}", TemplateType, ViewName, "_Layout", LocationBuilder));//
        }
        using (var Writer = new StringWriter())
        {
            //ViewResult.View.Render(new ViewContext(
            //  Context,
            //  ViewResult.View,
            //  (Controller != null) ? Controller.ViewData : (Model != null) ? new ViewDataDictionary(Model) : new ViewDataDictionary(),
            //  (Controller != null) ? Controller.TempData : new TempDataDictionary(), Writer), Writer);

            ViewResult.View.Render(new ViewContext(
                Context,
                ViewResult.View,
                Controller.ViewData,
                Controller.TempData, Writer), Writer);

            ViewResult.ViewEngine.ReleaseView(Context, ViewResult.View);

            // This must remove Tabs (\t) Returns (\r) and Newlines (\n)
            // Always making the quotes single makes sense for statically generated stuff - the only time when it wouldn't make sense is for more complex stuff or if it includes JS which i don't think
            // a statically generated one should ever?

            string result = Regex.Replace(Writer.GetStringBuilder().ToString().Replace("\"", "\'"), "(\\t|\\r|\\n)", string.Empty);

            // Currently, this process does not work well when initiated outside of a request (e.g. in the startup method or purely within a
            // hangfire task). This serves as a warning if it ever is (since it will return an empty string).

            if (result.Blank()) { throw new InvalidOperationException("There was an error rendering the " + ViewName + " template. This can happen if the template was initialized outside of the context of an actual request."); }
            else
            {
                return result;
            }
        }
    }
    catch (Exception ex)
    {
        // This could indicate an error in the underlying template
        // If there is an error on any of the underlying templates in a given class,
        // this can be called.
        Logging.Error(ex);
        return string.Empty;
    }
}

This works pretty well except for when I am trying to generate a template when I don't have a reference to a Controller.

I have also started looking into applying the third-party RazorEngine (https://antaris.github.io/RazorEngine) - but is this overkill? Is it even feasible to implement this in a project that also utilizes the built-in razor engine?

I am new to Springboot and also with their style of MVC architecture. I have one table calle Suppliers, with model like this:

public class Supplier {

    private Long id;
    private String name;
    private String description;
    private Long energy_type_id;
    private Date createdAt;
    private Date updatedAt;

    public Supplier(){

    }

    public Supplier(String name, String description, Long energy_type_id) {
        this.name = name;
        this.description = description;
        this.energy_type_id = energy_type_id;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Column(name = "name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Column(name = "description")
    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }



    @Column(name = "energy_type_id")
    public Long getEnergyTypeID() {
        return energy_type_id;
    }

    public void setEnergyTypeID(Long energy_type_id) {
        this.energy_type_id = energy_type_id;
    }

    @Column(name = "created_at")
    public Date getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(Date createdAt) {
        this.createdAt = createdAt;
    }

    @org.springframework.data.annotation.Version
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "updated_at")
    public Date getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(Date updatedAt) {
        this.updatedAt = updatedAt;
    }

}

I created a SupplierRepository :

@Repository
public interface SupplierRepository extends JpaRepository<Supplier, Long> {


}

and a DTO, but i never used it:

public class SupplierDTO {
    private Long id;
    private String name;
    private Long country_subdivision_id;
    private String phone;
    private  String address;
    private String mail;


    public Long getID()
    {
        return id;
    }

    public void setName(String name)
    {
        this.name=name;
    }

    public String getName()
    {
        return name;
    }

    public void setCountryID(Long country_subdivision_id)
    {
        this.country_subdivision_id= country_subdivision_id;
    }
    public Long getCountryID()
    {
        return country_subdivision_id;
    }

    public void setPhone(String phone)
    {
        this.phone = phone;
    }

    public String getPhone()
    {
        return phone;
    }

    public void setAddress(String address)
    {
        this.address=address;
    }

    public String getAddress()
    {
        return address;
    }

    public void setMail(String mail)
    {
        this.mail=mail;
    }

    public String getMail()
    {
        return mail;
    }



}

I have a table locality with name and ID, and because of M:M relationship i made another linking table caller SupplierLocality with the following model:

@Entity
@Table(name = "Suppliers_locality")
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "id")
public class SupplierLocality {

    private Long id;
    private Supplier Supplier;
    private Locality locality;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @ManyToOne
    @JoinColumn(name = "Supplier_id", referencedColumnName = "id")
    public Supplier getSupplier() {
        return Supplier;
    }

    public void setSupplier(Supplier Supplier) {
        this.Supplier = Supplier;
    }

    @ManyToOne
    @JoinColumn(name = "locality_id", referencedColumnName = "id")
    public Locality getLocality() {
        return locality;
    }

    public void setLocality(Locality locality) {
        this.locality = locality;
    }

    @Override
    public String toString() {
        return "SupplierLocality{" +
                "id=" + id +
                ", Supplier=" + Supplier.getId() +
                ", locality=" + locality.getId() +
                '}';
    }
}

I have created this controller wich returns me all entries from my Suppliers table:

@Controller
@RequestMapping("/suppliers")
public class SuppliersController {

    private final Logger logger = Logger.getLogger(getClass());

    @Autowired
    SupplierRepository supplierRepository;

    @RequestMapping(value = "sd",
            produces = {"application/json"},
             method = RequestMethod.GET)
    public ResponseEntity<List<Supplier>> getAllSuppliers() {
        return ResponseEntity.ok().body(supplierRepository.findAll());
    }
}

I want to make a POST request where I can add the locality id and which returns all the suppliers whose id match with locality id in the SupplierLocality table.

Please give me some advices because I want to understand all the process.

Thanks a lot!

I am trying to create a simple SelectList that renders as a dropdown for use in a Create form generated with RazorPages. For some reason, the SelectList renders with multiple="multiple" which results in all the options being shown in a frame with a scrollbar on the side instead of a dropdown. I believe the issue lies with my controller and the fact that I am trying to set both the "Text" and "Value" attributes of the SelectListItems with an anonymous type, as I have achieved the desired result when not setting those attributes.

A lot of this is very new to me, so if anyone has any general advice with regard to my code, I would appreciate it.

Here is my view model:

public class CreateFileViewModel
    {
        public SelectList EnrolleeId { get; set; }
        public SelectList GroupId { get; set; }

        [DataType(DataType.Date)]
        public DateTime StartDate { get; set; }

        public string Status { get; set; }
    }

Here is my controller:

public IActionResult TestCreate()
        {
            //query items for SelectLists
            var users = from u in _context.Users
                        orderby u.LastName
                        select u;

            var groups = from g in _context.Group
                         orderby g.Name
                         select g;

            // Loop through queries above and convert to collections of SelectListItems
            var enrolleeSelectListItems = from u in users
                                        select new SelectListItem()
                                        {
                                            Value = u.Id.ToString(),
                                            Text = u.LastName + ", " + u.FirstName + " " + u.MiddleName
                                        };

            var groupSelectListItems = from g in groups
                                         select new SelectListItem()
                                         {
                                             Value = g.ID.ToString(),
                                             Text = g.Name
                                         };

            //convert SelectListItem collections into SelectLists within view
            var cfvm = new Models.TestModels.CreateFileViewModel();
            cfvm.EnrolleeId = new SelectList(enrolleeSelectListItems, "Value", "Text");
            cfvm.GroupId = new SelectList(groupSelectListItems, "Value", "Text");

            return View(cfvm);
        }

This is the relevant portion of my view:

<div class="form-group">
                <label asp-for="EnrolleeId" class="control-label"></label>
                <select asp-for="EnrolleeId" asp-items="Model.EnrolleeId">
                    <option value="">Select</option>
                </select>
            </div>

and here is how it renders in the browser:

<select id="EnrolleeId" multiple="multiple" name="EnrolleeId" aria-invalid="false" class="valid">
                    <option value="">Select</option>
                    <option value="3e60fabd-6901-45a1-ae2a-5056d77f415c"></option>
                    <option value="40ce8b6e-62a5-4c3c-808b-90e36d633ec0"></option>
                    <option value="c0c49df2-da52-4a01-9a8a-47bab6f5496d"></option>
</select>

I have created an MVC application that was pointed at a local SQL Server Express database. Everything worked fine. I then deployed my application to Azure, changing the connection string to the below.But when i debug the application, from my PC Entity Framework seems to ignore the web.config file and tries to use SQL Server Express. I am not sure where it is picking up this connection from?

<connectionStrings>
    <add name="TrainProcess"
        connectionString="Server=tcp:traincliamapplication.database.windows.net;Database=TrainClaim;
                          User ID=xxxxxx@traincliamapplication;Password=xxxxx;Trusted_Connection=False;
                          Encrypt=True;" providerName="System.Data.SqlClient"/>                         
  </connectionStrings>

this has been bothering me for the last few days and think I am just overthinking things. I am opening up a bs modal dialog and passing it a value through the data-id attribute. Can pass the value with no problem; I can also store it in a hidden field/div whatever. However I need to pass that value to a razor function that brings back the rest of my record-set from the db and I am not using json to retrieve the records. I can convert the value but first must submit my form to get the value from the hidden field I stored it in. I can always post it to another page but that would defeat the purpose of using the modal. My question is since the 2 objects live in different states (server/client), how can I capture the ID as the modal is first launched with the ID. in this example I am passing the value to a div as well as hidden value. I can capture the hidden value only after I submit the form! Thanks.

 <button class="btn btn-info btn-lg open_mymodal" id="cafeID" data-id="@item.ID" data-toggle="modal" data-target="#myModal" data-yourparameter="@item.ID">Load</button>

  <div id="myModal" class="modal fade" role="dialog">
        <div class="modal-dialog">


            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Modal Header</h4>
                </div>
                <div class="modal-body">
                    <script type="text/javascript">

                    </script>


                    @{ 
                        <div id="getIco">

                        </div>
                    }

                    <form action="~/modals.cshtml" name="test" method="post">

                        <input type="hidden" class="form-control" id="IDRec" name="IDRec" />

                        <input type="text" class="form-control" id="getIco" name="getIco" value="" />
                        <input type="submit" name="name" value="submit" />
                    </form>

            @{
                   var recordID = request["IDRec"];
                   @recordID
             }

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>

        </div>
    </div>




$(document).ready(function () {
    $('#myModal').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget);
        var getmyID = button.data('id');
        var modal = $(this);
        modal.find('.modal-title').text('Here is the ID: ' + getmyID);
        modal.find('.modal-body #IDRec').val(getmyID);
        modal.find('.modal-body #getIco').val(getmyID);

    });
});

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.

I am creating a razor page website and i am working off the template microsoft offers... The template leaves spaces on the sides of pages when they use the @RenderBody() method (which comes with the template)... Can anyone help with fixing this in order to make it fullscreen.

Image example found here... http://codersblock.com/blog/images/dot-net-core-index-page.png

Thank you.