I get an error
Object reference not set to an instance of an object.
when I call my API that returns a view page. Without data passing to razor page everything is ok but I get error when I pass data to it.
This is my API:
public async Task<IActionResult> GetRazorPageHtml()
{
var viewPath = "/Template/Pages/paymentGateway.cshtml";
var viewResult = _razorViewEngine.GetView(viewPath, viewPath, false);
if (!viewResult.Success)
{
return NotFound();
}
var model = new PaymentGatewayModel
{
PaymentMethod = "Credit Card",
Amount = 100.00
};
var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
{
["PaymentMethod"] = model.PaymentMethod,
["Amount"] = model.Amount
};
var actionContext = new ActionContext(ControllerContext.HttpContext, ControllerContext.RouteData, ControllerContext.ActionDescriptor);
var output = new StringWriter();
var viewContext = new ViewContext(
actionContext,
viewResult.View,
viewData,
new TempDataDictionary(ControllerContext.HttpContext, _tempDataProvider),
output, // Use the same StringWriter instance
new HtmlHelperOptions()
);
await viewResult.View.RenderAsync(viewContext);
return Content(output.ToString(), "text/html");
}
This is my class for pass data of Razor page:
namespace Payment.Service.Presentation.Template.Pages;
public class PaymentGatewayModel
{
public string PaymentMethod { get; set; }
public decimal Amount { get; set; }
}
And finally this is my Razor page. When I code in this page autocomplete works after @Model
and suggests also Amount for example but I get error
Object reference not set to an instance of an object
What is the problem and how can I fix that?
@page
@model Payment.Service.Presentation.Template.Pages.PaymentGatewayModel
<h1>Payment Gateway</h1>
<p>Payment Method: @Model.Amount</p>
and also this my register section in program.cs :
builder.Services.AddRazorPages(options =>
{
// Set the root directory for Razor Pages
options.RootDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Pages");
});