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>
This question is related to
asp.net-mvc
asp.net-mvc-3
asp.net-mvc-4
asp.net-mvc-2
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();
Please try using following way.
@Html.Hidden("hdnFlag",(object) Convert.ToInt32(ViewBag.page_Count))
Without a view model you could use a simple HTML hidden input.
<input type="hidden" name="FullName" id="FullName" value="@ViewBag.FullName" />
You can transfer value from controller using ViewData[""]
.
ViewData["hdnFlag"] = userId;
return View();
Now, In you view.
@{
var localVar = ViewData["hdnFlag"]
}
<input type="hidden" asp-for="@localVar" />
Hope this will help...
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" })
if you are not using model as per your question you can do like this
@Html.Hidden("hdnFlag" , new {id = "hdnFlag", value = "hdnFlag_value" })
else if you are using model (considering passing model has hdnFlag property), you can use this approch
@Html.HiddenFor(model => model.hdnFlag, new { value = Model.hdnFlag})
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're going to reuse the value like an id or if you want to just keep it you can add a "new{id = 'desiredID/value'}) as its parameters so you can access the value thru jquery/javascript
@Html.HiddenFor(model => model.Car_id)
Source: Stackoverflow.com