Html.dropdownlist - calling javascript or controller / method directly?

In my MVC application, I have html.dropdownlist in my opinion. When choosing a change - I want the value to be passed to the method (which returns something like a list or JsonResult) in the controller.

Q1: How to do it?

 <%=Html.DropDownList("title", Model.Titleitems, "" )%>

Q2: Is this good practice (with the name of the controller / method in the view directly) or do I need to write a JavaScript function and call the appropriate controller / method from this JavaScript function? In this case, how can I write an Onchange or OnSelectionChanged event for the above html.dropdownlist control?

EDIT:

par1 is the selected dropdown value that I want to pass to this controller / method.

       public ActionResult GetMethod(string Par1)
        {
            //My code here 

            return Json(varValue, JsonRequestBehavior.AllowGet); 
        }

, JavaScript ( marteljn) JavaScript, URL-, URL-, .., /; , ?

+3
2

Q2 - Q1. MVC, , -, JavaScript, .
( ) :

  • Inline Event Handler ( )

    <%=Html.DropDownList("title", Model.Titleitems, new{@onchange = "YourJsFuncHere()"} )%>

  • JQuery,

    $("#title").bind("change",function(){
         //Your Code  
         //Use .on instead of bind if you are using JQuery 1.7.x or higher   
         //http://api.jquery.com/on/ 
    });
    

- AJAX

$.ajax({
  "url": "/Controller/Action/" + $("#title").val(),
  "type": "get",
  "dataType" : "json",
  "success": function(data){
    //Your code here
    //data should be your json result
  }
});

GetMethod(string Par1) GetMethod(string id) , Par1.

, , , 1) AJAX ( firebug, , ) 2) ( Global.asax.cs, .

+6
$(function(){
  $("#title").change(function(){
   var selectedVal=$(this).val();
   $.getJSON("UserController/YourAction",{ id: selectedVal} , function(result ){
       //Now you can access the jSon data here in the result variable
   });

 });

});

, Action, YourAction UserController, JSON

public ActionResult YourAction(int id)
{
  //TO DO : get data from wherever you want. 

   var result=new { Success="True", Message="Some Info"};
   return Json(result, JsonRequestBehavior.AllowGet); 

}
+2

All Articles