In this article I will explain with an example, how to set Label value using jQuery in ASP.Net MVC Razor.
This article will illustrate how to access and set value of Label element created using Html.Label and Html.LabelFor helper functions in ASP.Net MVC Razor.
Note: For beginners in ASP.Net MVC, please refer my article ASP.Net MVC Hello World Tutorial with Sample Program example.
 
 
Controller
The Controller consists of the following Action method.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
}
 
 
View
The View consists of a Label created using Html.Label helper function. In order for the Label to be accessible using jQuery, the ID attribute needs to be set.
Note: If the Label value is left Blank in the Html.Label function, the Label will not be created and thus jQuery will not be able to access it.
 
Then inside the jQuery document ready function, the Label is accessed using its ID and the value is set.
Note: In similar way, ID needs to be specified for the Html.LabelFor function.
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    @Html.Label("Name", new { @id = "lblName" })
 
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#lblName").html("Mudassar Khan");
        });
    </script>
</body>
</html>
 
 
Downloads