I have a .NET MVC CORE 5 application and in the Create.cshtml view, I want some of the fields in the form to be hidden so that users cannot set the values.
Instead, I want to use JavaScript to set the values for those fields.
Suppose the Create.cshtml currently has a field like this:
<div class="form-group">
<label asp-for="Hremail" class="control-label"></label>
<input asp-for="Hremail" class="form-control" />
<span asp-validation-for="Hremail" class="text-danger"></span>
</div>
The browser page source will be like this:
<div class="form-group">
<label class="control-label" for="Hremail">Hremail</label>
<input class="form-control" type="text" id="Hremail" name="Hremail" value="" />
<span class="text-danger field-validation-valid" data-valmsg-for="Hremail" data-valmsg-replace="true"></span>
</div>
One approach I might try is to use the JavaScript document.getElementById("Hremail").value =
to set the value myself.
However, I don't know how to make that field hidden for only that one view except to use JavaScript on page load to make the type be a hidden field.
Or maybe I can make the entire div tag surrounding it not be visible, or maybe even display: none.
I do see how to make the field hidden for all views by changing the model with the [HiddenInput] attribute; but I only want it hidden for that one view.
That's according to this:
https://docs.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms?view=aspnetcore-6.0
Another way I can think of is to remove the MVC generated tag helper and replace it with an HTML helper as is done here:
Maybe there is a better way altogether.
Does anyone have any suggestions on this?
thanks
<form asp-action="NewLeave">
. . .
<div class="form-group">
<input type="submit" value="NewLeave" class="btn btn-primary" />
</div>
</form>
Well, since I want JavaScript to act on the fields that I hide, I plan to change the input element to something like:document.NewLeave.submit();
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> NewLeave([Bind("Created,SupervisorApproval,SupervisorApprovalDate,HrApproval,HrName . . . ")] LeaveRequest leaveRequest)
{
if (ModelState.IsValid)
{
_context.Add(leaveRequest);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(leaveRequest);
}
So, is changing the input type to button, adding an onclick event and a function, having a submit command at the end of that function, and keeping the value="NewLeave", the best way to proceed?<input type="submit" value="NewLeave" class="btn btn-primary" />
I leave the form submit alone. I can set the hidden fields before the user wants to submit.
Open in new window
Even if you hide it, you need to make sure you do not accept the input on the back end.