Home > Blockchain >  How do I set the default value to a hidden input box using ASP.NET MVC?
How do I set the default value to a hidden input box using ASP.NET MVC?

Time:01-05

How can do I set the default value to a hidden input box in html page using ASP.NET MVC.

CodePudding user response:

Seems you are trying to set hidden value on asp.net MVC. You could try below way.

Model:

public class HiddenValueModel
    {
        public int HiddenValueId { get; set; }
        public String HiddenValueName{ get; set; }
    }

Load Default View From Controller:

 public IActionResult HiddenValueExample()
        {
            return View();
        }

View:

@model MVCApps.Models.HiddenValueModel


@{ ViewBag.Title = " "; }

<h2>Hidden Value Example </h2>
<hr />

@using (Html.BeginForm("HiddenValueExamplePost", "StackOverFlow"))
{


    <table >
        <tr><th>HiddenValueName </th><td id="HiddenValueName"> @Html.TextBoxFor(r => Model.HiddenValueName, new { @class = "form-control" })</td></tr>
        <tr><th>HiddenValue Id Which Is Hidden</th><td id="HiddenValueId"><input type="hidden" id="HiddenValueId" name="HiddenValueId" value="01052022" /></tr>
    </table>


    <input id="Button" type="submit" value="Save"  style="margin-left:1091px" />
}

Note: Here you could see HiddenValueId we have set the value into the feild and keep that hidden. But when you would submitted the value to the controller it would be there. Additionally, if you want to bind the hidden value from your backend you can use this way @Html.HiddenFor(m => m.HiddenValueId). You could also have a look more details on enter image description here

Hope it would guided you accordingly.

CodePudding user response:

Creating a Hidden Field in ASP .NET MVC

Studentmodel:

public class Student{
public int StudentId { get; set; }
public string StudentName { get; set; }}

HiddenFor() in Razor View:

@model Student @Html.HiddenFor(m => m.StudentId)

Html Result :

<input data-val="true"
 data-val-number="The field StudentId must be a number."
 data-val-required="The StudentId field is required."
 id="StudentId"
 name="StudentId"
 type="hidden"
 value="" />

Html.Hidden() :

@model Student
@Html.Hidden("StudentId")

Html Result :

<input id="StudentId" name="StudentId" type="hidden" value="1" />

CodePudding user response:

Basic Helper (@Html.Hidden())

If you want a Hidden Field with its value set you can try this:

@Html.Hidden("Jeremy", "Thompson")

The Hidden Field's name will be "Jeremy", and the value of the Hidden Field will be "Thompson".

Strongly Typed Helper (@Html.HiddenFor()) / Model Binding

The strongly typed helper contains 2 parameters:

  1. Hidden Field name which is the name of a Model Property.
  2. Value of Hidden Field (if we want to set the value from the view).

Declaration of Hidden Field using strongly typed helper:

@Html.HiddenFor(m => m.StudentID, new { Value = "1" })

Ref

  •  Tags:  
  • Related