How to pass variable from jquery to code in c#

前端 未结 2 510
醉梦人生
醉梦人生 2021-01-16 08:13

in my page i have an int variable name mySerial and i want to pass a value from a script

mySerial =ui.item.Serial is not working

相关标签:
2条回答
  • 2021-01-16 08:46

    You could pass this variable as query string parameter to some controller action:

    <script type="text/javascript">
        var mySerial = '12345';
        $.ajax({
            url: '@Url.Action("Foo", "Home")',
            type: 'POST',
            data: { mySerial: mySerial },
            success: function(result) {
                alert('success');
            }
        });
    </script>
    

    and the Foo action:

    [HttpPost]
    public ActionResult Foo(string mySerial)
    {
        ... do something with the serial here
    }
    

    Another possibility is to perform a redirect if you don't want to use AJAX:

    <script type="text/javascript">
        var mySerial = '12345';
        var fooUrl = '@Url.Action("Foo", "Home")';
        window.location.href = fooUrl + '?mySerial' + encodeURIComponent(mySerial);
    </script>
    

    Or maybe I misunderstood your question and you want to assign your javascript variable to some value coming from the view model? In this case:

    <script type="text/javascript">
        var mySerial = @Html.Raw(Json.Encode(Model.MySerial));
    </script>
    
    0 讨论(0)
  • 2021-01-16 08:47

    you could pass value from your jquery to controller action like this ...

    $(document).ready(function()
    {
        var postdata  = { name: "your name", Age: "your age" };// you can pass control values 
        $.ajax({
            ur: /home/index,
            data: postdata,
            success: function(returndata)
                 {
                    // do something here for the return data...
                  }
             });  
    });
    

    in your controller

    public ActionResult PostedDAta(string myname, string myage)
    {
                // do somethign here and return Json back to Jquery code
                return Json(data,JsonRequestBehaviour.AllowGet);  
    }
    
    0 讨论(0)
提交回复
热议问题