Reputation: 191
I am trying to Hide or Show filed on the MVC form base of a value stored in the Viewbag. the value of the Viewbag is a database return. I can see the value of the Viewbag in my JavaScript but when I run the form Hide/Show functionality is not working. I am missing something can anyone help
CHTML code
<div class="form-group" id="SharedAssetShared" style="display:none">
<div class="form-group">
<div class="row">
<div class="col-md-2">
<label class="control-label ">If yes, what is the Legal basis for sharing? </label>
</div>
<div class="col-md-10">
<input asp-for="LegalBasisforSharing" class="form-control" />
<span asp-validation-for="LegalBasisforSharing" class="text-danger"></span>
</div>
</div>
</div>
Javascript Code
$(document).ready(function () {
divAsset();
});
function divAsset() {
var AssetShared1 = '@ViewBag.AssetShared';
if (AssetShared1 == 'true') {
$("#SharedAssetShared").show();
}
else {
$("#SharedAssetShared").hide();
}
}
C# Code to stored Viewbag value
public async Task<IActionResult> Edit(int? id)
{
var asset = await _context.VwAllUserAssets.Where(x => x.Id == id).FirstOrDefaultAsync();
ViewBag.AssetShared = asset.AssetShared;
return View(asset);
}
Upvotes: 0
Views: 675
Reputation: 43890
You should change viewbag assignment:
ViewBag.AssetShared = asset.AssetShared.ToString();
remove
style="display:none"
and in your javascrtipt
if (AssetShared1 == 'True') {
$('#SharedAssetShared').css("display","block");
}
else {
$('#SharedAssetShared').css('display','none');
}
but if you use bootstrap better to use:
if (AssetShared1 == 'True') {
$('#SharedAssetShared').removeClass("d-none");
}
else {
$('#SharedAssetShared').addClass("d-none");
}
Upvotes: 1
Reputation: 431
Try logging your AssetShared1 in browser console.
console.log(AssetShared1);
If it says True like mine does change your code to:
if (AssetShared1 == 'True') {
$("#SharedAssetShared").show();
}
Upvotes: 0