I want to set the value of a hidden field from a controller.How can i do this?
In view part i have given like this..
<div>
@Html.Hidden("hdnFlag", null, new { @id = "hdnFlag" })
</div>
There are two Hidden Fields. The Hidden Field for the Name value is created using Html. HiddenFor function while the Hidden Field for the Country value is created using Html. Hidden helper function and it is assigned value using ViewBag object.
If you refresh the page or click on a hyperlink that does a GET, then the value will be lost or revert to the designer-generated default. Back to your question, if you have a designer-generated HiddenField (in the aspx file), it should automatically set the value on postback.
You could set the corresponding value in the ViewData/ViewBag
:
ViewData["hdnFlag"] = "some value";
But a much better approach is to of course use a view model:
model.hdnFlag = "some value";
return View(model);
and use a strongly typed helper in your view:
@Html.HiddenFor(x => x.hdnFlag, new { id = "hdnFlag" })
Please find code for respected region.
Controller
ViewBag.hdnFlag= Session["hdnFlag"];
View
<input type="hidden" value="@ViewBag.hdnFlag" id="hdnFlag" />
JavaScript
var hdnFlagVal = $("#hdnFlag").val();
Without a view model you could use a simple HTML hidden input.
<input type="hidden" name="FullName" id="FullName" value="@ViewBag.FullName" />
You need to write following code on controller suppose test is model, and Name, Address are field of this model.
public ActionResult MyMethod()
{
Test test=new Test();
var test.Name="John";
return View(test);
}
now use like like this on your view to give set value of hidden variable.
@model YourApplicationName.Model.Test
@Html.HiddenFor(m=>m.Name,new{id="hdnFlag"})
This will automatically set hidden value=john.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With