G.S Abhaypal G.S Abhaypal - 1 year ago 72
C# Question

Not able to render label tag on a view dynamically

I have below piece of code in


<div class="row">

<input type="text" placeholder="Enter POR ID" id="porID" class="col-md-2 input-sm" name="porTextBox">
<button class="btn btn-primary col-md-2 btn-sm" style="margin-left:15px;width:150px;" type="submit" id="btnCreateTFSItems"><strong>Create TFS Items</strong></button>
@if (TempData["formState"] != null)
//@Html.Label("lblsuccess", "Successfully created TFS Work Items!")
<label id="lblsuccess" style="color:green; visibility:visible"> Successfully created TFS Work Items!</label>

and the button is calling the below function in script tag :

<script type="text/javascript">
$(document).ready(function (e) {

$('#btnCreateTFSItems').click(function () {
var txt = $('#porID');
var errorLabel = $('#lblError');
if (txt.val() != null && txt.val() != '') {

url: '@Url.Action("CreateWorkItems", "Tables")',
type: 'POST',
data: { 'porTextBox': $('#porID').val() }
// alert('Successfully added');
else {
errorLabel.text("Please enter valid PORID");
return false;

$("#porID").keypress(function (e) {
var errorLabel = $('#lblError');
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;

The problem is in
file, it is checking the condition but its not adding the label. The reason may be because page is not refreshing to render the label. I am new to UI development so I have tried certain options which i found on net but wasn't able to make it work. Is there any way i can achieve this ?

Answer Source

The reason may be because page is not refreshing to render the label.

Exactly. You do an Ajax request to the server with JQuery(client script) and expect that the Razor code (server code) was executed to display the label. This doesn't work, because the server code doesn't know anything about the client code.

The solution is to display the label via JQuery. Render it by default, but hide it with CSS (display:none). After the request was successful, you can show the label by setting the CSS display property to "block" or "inline" using JQuery.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download