user10099944
user10099944

Reputation:

How can I make variable global in View?

I need to define below code as a global variable in the View and then I could use that value in my separate JS code. I don't know how to do this, I tried various things.

<td class="choice">

       @Html.TextBoxFor(modelItem => item.ManualDate, new { @type = "date", @class = "form-control datepicker" }) //I want this @Html... to be global and available in .js file
</td>

So this part of my View should be declared somewhere on the top of partial View? In curly brackets?

@{
    ViewBag.Title = "myTitle";
    Layout = "~/Views/Shared/_Layout.cshtml";
    var globalVar = "@Html.TextBoxFor(modelItem => item.ManualDate, new { @type = 'date', @class = 'form-control datepicker' })";

}

I refer to it in .js file but it doesn't work properly (in 'choice' data field string is showed instead of razor element):

finalChoice.innerHTML = '@Model.globalVar'

Upvotes: 0

Views: 452

Answers (1)

Karney.
Karney.

Reputation: 5031

The razor syntax like @Html.TextBoxFor and @Model can only be parsed by the server, not JavaScript. Using variables in @{//...} will be parsed as a string. The JavaScript file in the parent page can directly call the elements in the partial view.

@Html.TextBoxFor can be placed in the view. But if you don’t want to show it in the view, please set its style to hide. Then you can get this element via its id.

In _part.cshtml(partial view)

<div id="part">
  @Html.TextBoxFor(modelItem => modelItem.ManualDate, new { @type = "date", @class = 
  "form-control datepicker" })
</div>

example

Upvotes: 3

Related Questions