[javascript] How to pass a value to razor variable from javascript variable?

How to pass a value to razor variable from javascript variable, is it possible asp.net mvc razor view engine?

@{
    int a = 0;
}

<script>
    var b = ...
    @a = b;
</script>

This question is related to javascript c# razor

The answer is


I see that this problem was discussed some time ago, but if anyone 'll meet with this again, here is my solution:

In your *.cshtml View file:

<script>
var data = JsFunction("@Html.Raw(Model.Path)");
$(function () {
    $("#btn").click(function () {
        var model = { Id: '@Html.Raw(Model.Id)', Data: data }
        $.ajax({
            type: "POST",
            url: "/Controller/Action",
            data: model,
            datatype: "html",
            success: function() {
                console.log('Success');
            }
        });
    });
});
</script>

JavaScript variable model is something that I need to pass to Razor ViewModel. It can be done with ajax request. You just need to have proper argument/s in your action, that matches Json object created in JavaScript.

Hope it'll help someone!


But it would be possible if one were used in place of the variable in @html.Hidden field. As in this example.

@Html.Hidden("myVar", 0);

set the field per script:

<script>
function setMyValue(value) {
     $('#myVar').val(value);       
}
</script>

I hope I can at least offer no small Workaround.


Okay, so this question is old... but I wanted to do something similar and I found a solution that works for me. Maybe it might help someone else.

I have a List<QuestionType> that I fill a drop down with. I want to put that selection into the QuestionType property on the Question object that I'm creating in the form. I'm using Knockout.js for the select binding. This sets the self.QuestionType knockout observable property to a QuestionType object when the user selects one.

<select class="form-control form-control-sm"
    data-bind="options: QuestionTypes, optionsText: 'QuestionTypeText', value: QuestionType, optionsCaption: 'Choose...'">
</select>

I have a hidden field that will hold this object:

@Html.Hidden("NewQuestion.QuestionTypeJson", Model.NewQuestion.QuestionTypeJson)

In the subscription for the observable, I set the hidden field to a JSON.stringify-ed version of the object.

self.QuestionType.subscribe(function(newValue) {
    if (newValue !== null && newValue !== undefined) {                       
        document.getElementById('NewQuestion_QuestionTypeJson').value = JSON.stringify(newValue);
    }
});

In the Question object, I have a field called QuestionTypeJson that is filled when the user selects a question type. I use this field to get the QuestionType in the Question object like this:

public string QuestionTypeJson { get; set; }

private QuestionType _questionType = new QuestionType();
public QuestionType QuestionType
{
    get => string.IsNullOrEmpty(QuestionTypeJson) ? _questionType : JsonConvert.DeserializeObject<QuestionType>(QuestionTypeJson);
    set => _questionType = value;
}

So if the QuestionTypeJson field contains something, it will deserialize that and use it for QuestionType, otherwise it'll just use what is in the backing field.

I have essentially 'passed' a JavaScript object to my model without using Razor or an Ajax call. You can probably do something similar to this without using Knockout.js, but that's what I'm using so...


Step: 1 Your Html, First Store the value in your localstorage using javascript then add the line like below ,this is where you going to display the value in your html, my example is based on boostrap :

<label for="stringName" class="cols-sm-2 control-
label">@Html.Hidden("stringName", "")</label>

Step:2 Javascript

 $('#stringName').replaceWith(localStorage.getItem("itemName"));

here is my solution that works:

in my form i use:

@using (Html.BeginForm("RegisterOrder", "Account", FormMethod.Post, new { @class = "form", role = "form" }))
  {

   @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })

   @Html.HiddenFor(m => m.quantity, new { id = "quantity", Value = 0 })

  }

in my file.js I get the quantity from a GET request and pass the variable as follows to the form:

    $http({
        method: 'Get',
        url: "https://xxxxxxx.azurewebsites.net/api/quantity/" + usr
    })
        .success(function (data){

            setQuantity(data.number);

            function setQuantity(number) {
                $('#quantity').val(number);
            }

        });

Razor View Server Side variable can be read to Client Side JavaScript using @ While and JavaScript client side variable can read to Razor View using @:


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to razor

Uncaught SyntaxError: Invalid or unexpected token How to pass a value to razor variable from javascript variable? error CS0103: The name ' ' does not exist in the current context how to set radio button checked in edit mode in MVC razor view @Html.DropDownListFor how to set default value Razor MVC Populating Javascript array with Model Array How to add "required" attribute to mvc razor viewmodel text input editor How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas Multiple radio button groups in MVC 4 Razor How to hide a div element depending on Model value? MVC