wingyip
wingyip

Reputation: 3536

Create variable in view and assign

I need to create a string variable in my View and assign to a hidden input which is bound to a property on my strongly typed model

I guess it is something like

@Html.HiddenFor(m=>m.nodelist, new {@value = myVar})

however not working

Upvotes: 0

Views: 76

Answers (3)

Ankush Jain
Ankush Jain

Reputation: 6999

use simple html hidden field and keep it's name same as property name. This works perfectly

@{
string val=myVar;
}

<input type="hidden" name="nodelist" value="@val" />

Upvotes: 0

TechnoBrat
TechnoBrat

Reputation: 277

Is myVar a javascript variable?

You could assign your hidden field an ID property.

@Html.HiddenFor(m=>m.nodelist, new {@id = "hdnNodeList"})

and using javascript or jquery you could do the following

$('#hdnNodeList').val(myVar);

or if myVar is a C# variable you could try the following (this will render an html output, although you could do it here, its better to assign a value to m.nodelist in your controller if possible)

$('#hdnNodeList').val('@myVar');

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

Don't try to be setting the @value attribute on the html helper. That's not how those helpers have been designed to work. They have been designed to bind to the value of the corresponding property on the view model you passed to this view.

So it's as simple as:

@Html.HiddenFor(m => m.nodelist)

and in the controller action rendering this view you would assign the corresponding property on the view model to the desired value:

public ActionResult Index()
{
    MyViewModel model = ...
    model.nodelist = someVariable;
    return View(model);
}

If on the other hand this variable is actually a javascript variable then you should obviously use javascript to assign it to the hidden field:

<script type="text/javascript">
    var myVar = 'some value';
    $('#nodelist').val(myVar);
</script>

or if you are not using jQuery:

<script type="text/javascript">
    var myVar = 'some value';
    document.getElementById('nodelist').value = myVar;
</script>

Upvotes: 2

Related Questions