0

How do i access variable "DataToBind" of One.cshtml page in Two.cshtml page?

One.cshtml

<script>
var DataToBind;

    $.ajax({
            url: "/Home/getDetails",
            type: "POST",
            dataType: "json",
            data: JSON.stringify({ agencyID: agencyID, salesID: saleID, DebtorID: debtorID, AccountNo: accountNO }),
            contentType: 'application/json; charset=utf-8',
            success: function (response) {
                DataToBind = response[0];

                window.location.href = "Two";
            }, error: function () {

                console.log("new error");
            }
        });
</script>

Two.cshtml

I get this error : Uncaught ReferenceError: DataToBind is not defined when i use "DataToBind" variable in this page.

  • 1
    Why in the world are you using ajax when you want to redirect (the whole pint of ajax is to stay on the **same** page!) –  Dec 08 '17 at 12:28
  • I'm working on someone else's project. I don't know why there are doing this. I can't change the whole structure and the methodology of the project ... !! – Hussam Cheema Dec 08 '17 at 12:43
  • I did it ... I stored the variable in session storage. – Hussam Cheema Dec 08 '17 at 15:45
  • No but what you can do is get rid of the pointless ajax call, make a normal submit and in the post method, redirect and pass the value to the other method –  Dec 08 '17 at 23:04

1 Answers1

1

As I understand you are trying to get some value and use it in another page. This is a bit unusual scenario, but you best shot is

<script>
var DataToBind;

$.ajax({
        url: "/Home/getDetails",
        type: "POST",
        dataType: "json",
        data: JSON.stringify({ agencyID: agencyID, salesID: saleID, DebtorID: debtorID, AccountNo: accountNO }),
        contentType: 'application/json; charset=utf-8',
        success: function (response) {
            c= response[0];

            window.location.href = "Two?data=" + DataToBind;
        }, error: function () {

            console.log("new error");
        }
    });

</script>

and in your page Two access this data

<script>
        var DataToBind =  @(Request.QueryString["data"])
        ...
     </script>

or another way

<script>
var DataToBind = @HttpContext.Current.Request.QueryString["data"]
...
</script>

and then you can use your DataToBind on Two.cshtml

Yuri
  • 2,820
  • 4
  • 28
  • 40