5

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.

  • 2
    It's moved to `HttpContext.Response.Body` - you need to supply your own `StreamWriter` though. – Dai Nov 01 '19 at 10:52
  • "If I want to just display the value of a variable in the web page" - ASP.NET Core does not have a concept of "web pages" so your question is difficult to answer if you're still thinking along the old lines of `*.asp` and `*.php` files. – Dai Nov 01 '19 at 10:53
  • I want to display it in a cshtml page. Please give some sample code. – Partha Mandayam Nov 01 '19 at 11:12
  • ok tell me how to display a simple message in a cshtml file – Partha Mandayam Nov 01 '19 at 11:27

2 Answers2

4

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?

Community
  • 1
  • 1
Ryan
  • 19,118
  • 10
  • 37
  • 53
1

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.