Partha Mandayam
Partha Mandayam

Reputation: 109

Why is there no Response.Write in asp.net core?

What's the workaround to display a simple message? If I want to just display the value of a variable in the web page tell me something similar to Response. Write.

Upvotes: 6

Views: 10097

Answers (2)

Andrew Crouse
Andrew Crouse

Reputation: 121

As easy way to do this is by using the page model to write your value to the output You do not need to use Response.write. Here is a simple demo using a Razor Page.

1) Create new Razor page called NewPage in your Pages folder.

2) In your page model (NewPage.cshtml.cs) create a new public string named message.

    public class NewPageModel : PageModel{
        public string message;

3) Assign the message variable a value in the OnGet/OnPost method.

    public void OnGet(){
        message = "Hello World";

4) In NewPage.cshtml write the model value to the output.

    @page
    @model MyProject.Web.Pages.NewPageModel
    @{
        Layout = null;
    }
    @Model.message

Your value will be shown in the output.

Upvotes: 1

Ryan
Ryan

Reputation: 20126

Response.Write uses System.Web namespaces and it is used in Asp.NET Framework not Asp.NET Core.

If I want to just display the value of a variable in the web page tell me something similar to Response. Write.

tell me how to display a simple message in a cshtml file

It is not clear where does the variable come from or where do you want to use the Response.Write.

If you want to pass data from controller to view, you could use ViewBag/ViewData

Action:

public IActionResult Index()
{
    ViewBag.Title = "hello";
    return View();
}

View:

@ViewBag.Title

If you want to just display a message in view you could use HttpContext.Response.Body.Write

public async Task Index()
{
      var str = "hello world";
      byte[] bytes = Encoding.ASCII.GetBytes(str);        
      await HttpContext.Response.Body.WriteAsync(bytes);
}

Refer to Is there an equivalent to "HttpContext.Response.Write" in Asp.Net Core 2?

Upvotes: 5

Related Questions