Joey Zhang
Joey Zhang

Reputation: 363

How to update label text through onclick event in ASP.net (Razor)?

I want to create a button so as to update a label's text after 'onclick'. I found some solutions achieved by 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 Razor view engine in ASP.net MVC?

Upvotes: 4

Views: 3832

Answers (3)

D&#225;vid Moln&#225;r
D&#225;vid Moln&#225;r

Reputation: 11583

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

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

... and in the view use it like this:

<label>@ViewBag.MyCustomTitle</label>

Upvotes: 0

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34160

You can have a property in your model like:

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
}

And in your view you should have your label like this:

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

P.S.: Change ControllerName to the appropriate name of your controller

Upvotes: 1

NicoJuicy
NicoJuicy

Reputation: 3528

Are you coming from a asp.net webforms background?

You should update the text with javascript. The runat="server" doesn't exist anymore and shouldn't be used according to MVC principles.

Upvotes: 3

Related Questions