I am working with a C# MVC Razor app where the previous person has written a dialog class containing a hidden field. The dialog class calls RenderPartial() which contains some razor code to create some output using the hidden field.
The issue is, the razor code needs to access the value set in the hidden field, but I cannot find an example on how to do it.
<input type="hidden" name="bob" value="123" class="bobsname" />
@{
this.ViewData.Add("BobKey:, 123); <-- hard coded
Html.RenderPartial("SomeDialog");
}
And in SomeDialog I can access the value using ViewData.ContainsKey("BobKey") etc.
Ideally, I'd like to get the value from the nearest hidden field with the class='bobsname' but also by nearest hidden field with name is also ok.
The reason for this is that the dialog is called from rows in a table when the user clicks on a field, so there may be multiple definitions of the hidden field but with different values.
Note: The value is not accessible via the model or viewbag.
Regards
you can use jQuery to accomplish this.
<script>
$(document).ready(function () {
// Find the nearest hidden field with class 'bobsname'
var nearestHiddenField = $(this).closest('tr').find('input.bobsname');
// If it's found, get its value
if (nearestHiddenField.length > 0) {
var bobValue = nearestHiddenField.val();
console.log('Value of the nearest hidden field with class "bobsname": ' + bobValue);
}
});
</script>
If you want to access the value of the nearest hidden field without Jquery, you can achieve this by making use of Razor variables.
@{
var bobValue = Request.Form["bob"];
this.ViewData.Add("BobKey", bobValue);
Html.RenderPartial("SomeDialog");
}
and In your "SomeDialog" partial view
<!-- SomeDialog.cshtml -->
<p>The value of the hidden field "bob" is: @ViewData["BobKey"]</p>