0

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".

2
  • 2
    How do you call TestId action from View? Please share that code as well. If you are using Form & Submit button then make sure your @Html.HiddenFor line is written inside Form Commented Dec 6, 2022 at 4:27
  • @Karan Have edited my question! I am using the Html.BeginForm for the form. Commented Dec 6, 2022 at 6:02

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

You can use @Html.Hidden

@using (Html.BeginForm())
{
    @Html.Hidden("id", "123456789" )
  
    <input type="submit" value="Submit" />
}

result:

enter image description here

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)

1 Comment

@Jessica Please have a look at my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.