1

I have tried this but nothing happened.

cshtml

@Html.DropDownList("UtilisateurId", ViewBag.Utilisateurs as SelectList, String.Empty, new { @class = "UserSelected" })

JS

$("#UserSelected").change(function () {
    alert("$(this).val() = " + $(this).val());
});

I get no error but it doesn't work.

Can someone please advise what is the best way to do?

2 Answers 2

1
$(document).ready(function(){  //wrap under document.ready
  $(".UserSelected").change(function () {  //put '.' here instead of '#' because its a class selector
    alert("dropdown value = " + $(this).val());
  });
});

Edit:-

As questioner put another question in comments section so i m answering it here. In order to call a action from jquery you can make a ajax call as :

View :-

  $(document).ready(function(){  
    $(".UserSelected").change(function () {  
    var serviceURL = '/AjaxTest/FirstAjax'; //here 'AjaxTest' is controller name and 'FirstAjax' is action name or you can also use @Url.Action() to specify url here

        $.ajax({
            type: "GET",
            url: serviceURL,
            data:{ param = $(this).val() },
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: successFunc,
            error: errorFunc
        });

        function successFunc(data, status) {     
            alert(data);
        }

        function errorFunc() {
            alert('error');
        }
      });
  });

Controller :

public class AjaxTestController : Controller
{
  //
  // GET: /AjaxTest/
  public ActionResult Index()
  {
    return View();
  }

  [HttpGet]
  public ActionResult FirstAjax(string param)
  {
    return Json("test", JsonRequestBehavior.AllowGet);
  }   
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! It works. Do you know how can I execute an action and passing the value as parameter instead of displaying the alert message, please?
@Sounouk.. i think above answer is enough if answer solved your question then accept it as answer so that answer help others also..thanks...
ATException, thank you very much! It works very well.
0

If the above answer doesn't work,Use this

    <script type="text/javascript">
$(document).ready(function(){
        $(".UserSelected").change(function () {
            alert("$(this).val() = " + $(this).val());
        });
});
</script>

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.