I am trying to pass a hidden value from View to Controller in ASP.NET Core.
@using (Html.BeginForm("PostTest", "Test", FormMethod.Post)
{
@Html.HiddenFor(model => model.id, new { @Value = "123456789" })
}
In my controller, I am receiving it as a model
public ActionResult TestId(ObjTest objTest)
{
string result = objTest.id;
Console.WriteLine(result)
}
This is my model:
public class ObjTest
{
public string id { get; set; }
}
However, I am unable to retrieve the value "123456789".
CodePudding user response:
Can you modify the code like this?
<form method="post">
<input type="hidden" asp-for="Id" value="123456789">
<input type="submit" value="Submit" />
</form>
Use the asp-for
attribute instead of @Html.HiddenFor
CodePudding user response:
You can use @Html.Hidden
@using (Html.BeginForm())
{
@Html.Hidden("id", "123456789" )
<input type="submit" value="Submit" />
}
result:
If you want to use @Html.HiddenFor
, you need to set the value in the get method, like below:
public ActionResult TestId()
{
var model = new ObjTest();
model.id = "123456789";
return View(model);
}
[HttpPost]
public ActionResult TestId(ObjTest objTest)
{
string result = objTest.id;
Console.WriteLine(result);
return View();
}
Then
@Html.HiddenFor(model => model.id)