How to update tag text via onclick event in ASP.net (Razor)?

I want to create a button to update the label text after "onclick". I found some solutions achieved using ASPX, but I want to use Razor.

//The following is achieved by ASPX

//View
<asp:label id="myLabel" runat="server" />

//Onclick event
myLabel.Text = "my text"; 

How to do this with the Razor view engine in ASP.net MVC?

+4
source share
3 answers

Are you coming from asp.net web forms background?

You must update the text using javascript. Runat = "server" no longer exists and should not be used in accordance with the principles of MVC.

+3
source

You may have a property in your model, for example:

ControllerNameModel
{
   ...
   public string LabelText {get; set;} = "my text"; //my text is the default value
}

Then in your controller you can change the label text:

public IActionResult ControllerName(ControllerNameModel model)
{
     model.LabelText = "new text for label"
     return View(model); // return the view with modified model
}

, , :

<label for="something">@Model.LabelText</label>

P.S.: _

+1

You can use a simple ViewBag for this. Set the value in the controller:

public ActionResult Index()
{
    ViewBag.MyCustomTitle = "Title"
    return View();
}

... and in the view, use it as follows:

<label>@ViewBag.MyCustomTitle</label>
0
source

Source: https://habr.com/ru/post/1676909/


All Articles