Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the value of a hidden field from a controller in mvc

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>
like image 390
user2156088 Avatar asked Jun 01 '13 08:06

user2156088


People also ask

How can get hidden field value in MVC controller?

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.

How do you keep a hidden field value on a postback?

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.


4 Answers

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" })
like image 83
Darin Dimitrov Avatar answered Oct 29 '22 09:10

Darin Dimitrov


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();
like image 36
Krunal Solanki Avatar answered Oct 29 '22 07:10

Krunal Solanki


Without a view model you could use a simple HTML hidden input.

<input type="hidden" name="FullName" id="FullName" value="@ViewBag.FullName" />
like image 7
mokumaxCraig Avatar answered Oct 29 '22 07:10

mokumaxCraig


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.

like image 6
sandeep modi Avatar answered Oct 29 '22 07:10

sandeep modi