1

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 Answers 2

4

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>
Sign up to request clarification or add additional context in comments.

3 Comments

My problem is that the variable is not exists in the java script,it exists in the page @{ int mySerial=0;}
@avi, in this case simply replace Model.MySerial in my example with mySerial.
Hey @DarinDimitrov... this was killing me... spent almost 1 hour trying to make the 'C#' string in my jQuery code encoded and finally found your answer with encodeURIComponent! I've been up-voting a lot of your answers! This one is no different. :D Thanks again.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.