简体   繁体   English

将javascript变量从视图传递到控制器并保存在另一个变量中

[英]Pass a variable of javascript from view to a controller and save in another variable

I want to know if it a way to pass a variable of javascript to a controller. 我想知道这是否是将javascript变量传递给控制器​​的方法。 What I'm trying to do is to have a variable in my controller that starts empty when the user sign in and in my view I will validate if the variable is empty or not, if it's empty a call a javascript prompt, where i save the text that I write in a javascript variable, but i don't know how to pass the text to my controller variable. 我想做的是在控制器中有一个变量,当用户登录时该变量开始为空,在我看来,我将验证该变量是否为空,如果为空,则调用javascript提示,将其保存在其中我在javascript变量中编写的文本,但是我不知道如何将文本传递给我的控制器变量。 This is what i'm trying in code: 这就是我正在尝试的代码:

The controller: 控制器:

 ViewData["Contenedor"] = contenedor;

I pass the variable to the ViewData in the view and validate if is empty or not.If its empty a call the prompt: 我将变量传递给视图中的ViewData并验证是否为空,如果为空则调用提示:

@if (ViewData["Message"] == null){
<script type="text/javascript">
        window.onload = function () {
        var contenedorID = prompt("Ingrese ID del Contenedor a Ingresar", "");
        -- Here I want to do something to pass my variable contenedorID to my controller variable contenedor ---
    };
</script>
@if (ViewData["Message"] == null){
<script type="text/javascript">
        window.onload = function () {
        var contenedorID = prompt("Ingrese ID del Contenedor a Ingresar", "");
        -- Here I want to do something to pass my variable contenedorID to my controller variable contenedor ---

@ViewData["Message"] = "variablevalue you want to pass"

    };
</script>

This is storing data in viewdata which will be accessible in the controller when you post back.This works with out changing any of your existing code. 这是将数据存储在viewdata中,当您回发时可以在控制器中访问它。这无需更改任何现有代码。

The cleaner way would be to do a ajax post or set the value in a hidden variable using @Html.HiddenFor as others have suggested. 较干净的方法是执行ajax发布或使用@ Html.HiddenFor设置隐藏变量中的值,如其他人所建议的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM