G.S Abhaypal G.S Abhaypal - 18 days ago 6
C# Question

Not able to render label tag on a view dynamically

I have below piece of code in

.cshtml
file.

<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>
}
</div>


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() != '') {
//alert('clicked');

$.ajax({
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');
errorLabel.text("");
//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
.cshtml
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

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.

Comments