admin管理员组

文章数量:1136168

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

@{
    int a = 0;
}

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

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>
Share Improve this question edited Feb 4, 2015 at 14:31 ndugger 7,5315 gold badges34 silver badges42 bronze badges asked Feb 4, 2015 at 8:55 user4208535user4208535 6
  • 2 You can't. You can "pass" a Razor variable to a JavaScript variable but not the other way around. – Andrei V Commented Feb 4, 2015 at 8:57
  • possible duplicate of How to pass JQuery variables to Razor? – J. Steen Commented Feb 4, 2015 at 8:58
  • 1 And, to nit pick, they're not "jquery" variables. They're javascript variables. – J. Steen Commented Feb 4, 2015 at 9:00
  • @J.Steen, well, you know.... – Andrei V Commented Feb 4, 2015 at 9:06
  • 1 @AndreiV Yes. I post it often. =) – J. Steen Commented Feb 4, 2015 at 9:07
 |  Show 1 more comment

8 Answers 8

Reset to default 86

You can't. and the reason is that they do not "live" at the same time. The Razor variables are "Server-side variables", and they don't exist anymore after the page was sent to the "Client side".

When the server gets a request for a view, it creates the view with only HTML, CSS and JavaScript code. No C# code is left, it's all get "translated" to the client-side languages.

The JavaScript code DOES exist when the view is still on the server, but it's meaningless and will be executed by the browser only (Client side again).

This is why you can use Razor variables to change the HTML and JavaScript but not vice versa. Try to look at your page source code (CTRL+U in most browsers), there will be no sign of C# code there.

In short:

  1. The server gets a request.

  2. The server creates or "takes" the view, then computes and translates all the C# code that was embedded in the view to CSS, JavaScript, and HTML.

  3. The server returns the client-side version of the view to the browser as a response to the request. (there is no C# at this point anymore)

  4. the browser renders the page and executes all the JavaScript

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...

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!

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);
            }

        });

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"));

Yes You Can

Asp.net MVC razor

I have 2 Input

 <input id="TXTCount" type="number" readonly="readonly" class="form-control text-center text-bold" step="1" min="0" max="10000" value="1" inputmode="numeric" />

 <input id="TXTTOTal" type="number" readonly="readonly" class="form-control text-center text-bold" step="1" min="0" max="10000" value="1" inputmode="numeric" />

C# In view

  @{string WatsMSG = "xxx";}

And WhatsApp Link

 <a class="btn btn-success" id="WatsSendApi" href="https://api.whatsapp.com/send?phone=0000&text=@WatsMSG">
    <b class="text-black" style="font-size:small"> whatsapp </b><i class="fa fa-whatsapp" style="color:white"></i> </a>

And In jQuery

 <script>
                                        $("#WatsSendApi").click(function () {
                                            var StringMSG;
                                            StringMSG=("Ineed : ");
                                            StringMSG += (" Item Name : ");
                                            StringMSG +='@item.ITName' ;
                                            StringMSG += (" Count: ");
                                            StringMSG += $('#TXTCount').val();
                                            StringMSG += (" Price: ");
                                            StringMSG += '@item.ITPrice';
                                            StringMSG += (" Total: ");
                                            StringMSG += $('#TXTTOTal').val();
                                            alert(StringMSG);
                                            this.href = this.href.replace("xxx", StringMSG);
                                        });
                                    </script>

I am passing script value And Model value to C# string

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 @:

本文标签: cHow to pass a value to razor variable from javascript variableStack Overflow