Avatar of Babak Sekandari
Babak Sekandari
Flag for United States of America asked on

How do I make fields in an MVC View, hidden, and set their values with JavaScript?

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>

Open in new window

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>

Open in new window


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:

https://www.tutlane.com/tutorial/aspnet-mvc/create-or-use-hidden-fields-in-asp-net-mvc-with-html-helpers-example


Maybe there is a better way altogether.

Does anyone have any suggestions on this?

thanks













JavaScript.NET Programming.NET MVC

Avatar of undefined
Last Comment
Scott Fell

8/22/2022 - Mon
Scott Fell

You can just add a class, it could be named anything, as long as you name it the same for the label and input and then use css or javascript to hide any element with that has that class.

<div class="form-group">
   <label class="control-label hide" for="Hremail">Hremail</label>
   <input class="form-control hide" type="text" id="Hremail" name="Hremail" value="" />
   <span class="text-danger field-validation-valid" data-valmsg-for="Hremail" data-valmsg-replace="true"></span>
</div>

Open in new window

Even if you hide it, you need to make sure you do not accept the input on the back end.
lenamtl

Hi,

Even if the field hidden with CSS or JS this will still display the content from browser console.
So you may want to encrypt the data to prevent user changing the value.
Or hide it completely using server side code if not required by the form in some case.
Scott Fell

That is more of a side note than addressing the issue. Really it should be assumed that you never trust data and should always verify input on the server side. But this question is how to hide.
Your help has saved me hundreds of hours of internet surfing.
fblack61
Babak Sekandari

ASKER
Hi Scott,
   Thank you.
   I just want to make sure of some things:

First:
   If I set the CSS, display: none for a class on the div, the form should still submit as it normally would. Correct?

Second:
   Suppose the form in the .cshtml is this:
<form asp-action="NewLeave">
. . .
    <div class="form-group">
          <input type="submit" value="NewLeave" class="btn btn-primary" />
     </div>
</form>

Open in new window

Well, since I want JavaScript to act on the fields that I hide, I plan to change the input element to something like:

    <div class="form-group">
          <input type="button" onclick="return SaveLeaveRecord();" value="NewLeave" class="btn btn-primary" />
     </div>

Then at the end of the SavePersonRecord() function I plan to have some kind of code like this:
document.NewLeave.submit();

Open in new window


Is that the best way to do it?
Will the form know to submit to the NewLeave action method as it had before?
Since I'm using JavaScript to set the fields, then I don't see any other way than to change the input type from submit to button and have an onclick event which calls a functions, sets the fields, then submits.
Should I remove or keep the,
value="NewLeave

Should it be,
onclick="return SaveLeaveRecord();"
or remove the word, return:
onclick="SaveLeaveRecord();"

The NewLeave action method looks like:
 [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);
        }

Open in new window

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?

ASKER CERTIFIED SOLUTION
Scott Fell

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Babak Sekandari

ASKER
Hi Scott,

   That's a great idea.
   If I understand you correctly, I leave the type="submit" as is.
<input type="submit" value="NewLeave" class="btn btn-primary" />

Open in new window

   I leave the form submit alone. I can set the hidden fields before the user wants to submit.

   For example, on the page load event, I could have some of the hidden fields set.
   Then for other hidden fields that require concatenation or other manipulation from visible fields, I can have that happen on some onblur event or other user action event.
   Right?
Scott Fell

That sounds right.

If any of the hidden fields will never change, I would remove them from the form, and just manually set the variable in the server side code. 
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.