Skip to content
Advertisement

Show or Hide Field on MVC form base on the value of Viewbag using JavaScript

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);
}

Advertisement

Answer

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");
    
  }
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement