1

I'm trying to call a function with the value of the selected index of a drop-down menu that returns an array and append the result to my div 'content', but I can't figure how can I make this work? I can't use the variable test in my function.

@section Scripts {
    <script>
        var test = document.getElementById("drop-down").value
        $("#content").append("<h1>" + @DB.AfficherReponses(test)[0] + "</h1>")
    </script>
}
1
  • 1
    You need to use ajax to call a server method and return a response (or pass all values of DB.AfficherReponses to the view and assign it to a javascript array) Commented May 4, 2017 at 2:14

1 Answer 1

1

You can pass C# Method value in JavaScript/jQuery. But you can't pass JavaScript/jQuery value into C# Method.

Possible:

@{var str="Hi";}

@section Scripts {
    <script>        
        $("#content").append("<h1>'" + @str + "'</h1>")
    </script>
}

Impossible :

@section Scripts {
    <script>
        var test = document.getElementById("drop-down").value
         @DB.AfficherReponses(test)
    </script>
}

But you can do by ajax calling.

Example:

//controller
public class JsonDemoController : Controller  
    {  
        public JsonResult WelcomeNote(string name)  
        {  
           string output = "Welcome " +name;    
            return Json(output, JsonRequestBehavior.AllowGet);  
        }  
     }  

//view

@section Scripts {
    <script>
        var test = document.getElementById("drop-down").value
         $("#content").append("<h1>'" + getWelcomeNote(test) + "'</h1>")

function getWelcomeNote(name) {
    var json;
    $.ajax({
        url: "/JsonDemo/WelcomeNote/" + anme,
        dataType: 'json',
        async: false
    }).done(function (data) {
        json = data;
    });
    return json;
}

    </script>
}
Sign up to request clarification or add additional context in comments.

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.