Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在ASP.net(Razor)中通过onclick事件更新标签文本?_C#_Asp.net_Asp.net Mvc_Razor - Fatal编程技术网

C# 如何在ASP.net(Razor)中通过onclick事件更新标签文本?

C# 如何在ASP.net(Razor)中通过onclick事件更新标签文本?,c#,asp.net,asp.net-mvc,razor,C#,Asp.net,Asp.net Mvc,Razor,我想创建一个按钮,以便在“onclick”之后更新标签的文本。我发现了一些使用ASPX实现的解决方案,但我想使用Razor //The following is achieved by ASPX //View <asp:label id="myLabel" runat="server" /> //Onclick event myLabel.Text = "my text"; //以下是由ASPX实现的 //看法 //Onclick事件 myLabel.Text=“我的文本”;

我想创建一个按钮,以便在“onclick”之后更新标签的文本。我发现了一些使用ASPX实现的解决方案,但我想使用Razor

//The following is achieved by ASPX

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

//Onclick event
myLabel.Text = "my text"; 
//以下是由ASPX实现的
//看法
//Onclick事件
myLabel.Text=“我的文本”;

如何在ASP.net MVC中使用Razor视图引擎实现这一点?

您是否来自ASP.net webforms背景


您应该使用javascript更新文本。runat=“server”已不存在,根据MVC原则,不应使用它。

您的模型中可以有如下属性:

ControllerNameModel
{
   ...
   public string LabelText {get; set;} = "my text"; //my text is the default value
}
然后,您可以在控制器中更改标签文本:

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>
<label>@ViewBag.MyCustomTitle</label>
@Model.LabelText

注意:将控制器名称更改为控制器的适当名称

您可以使用一个简单的ViewBag来完成此操作。在控制器中设置值:

public ActionResult Index()
{
    ViewBag.MyCustomTitle = "Title"
    return View();
}
。。。在视图中,按如下方式使用:

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

Wht sql.net在标题中?这是一个拼写错误,将修复它不,它在服务器端。如果您想使用onclick,那么您将需要javascript。如果是这种情况,请更新您的问题。