Home > Net >  How to pass javaScript value in view page to Controller Action parameter, when change drop down list
How to pass javaScript value in view page to Controller Action parameter, when change drop down list

Time:03-13

I want to pass student Id in my controller action, I used JsonResult action, I catch student id but can't pass in action,

this is my JavaScript code ,

<script type="text/javascript">
    $(document).ready(function () {
        $("#sId").change(function(){
            var studentId = $(this).val();
            debugger
            $.ajax({
            type:"post", 
            url:"/Department/GetDeptName/"   studentId,
            contentType:"html",
            success:function(response){
            debugger
            $("#dId").empty();
            $("#did").append(response);
            }
            })
        })
    });
</script>

And I have a Dropdown list, I pass my list fron database using ViewBag. When I select a student name then need to pass his/her department name. This is the view code

<div >
            <div >
                <label asp-for="Name" >Student Name</label>
                <select asp-for="Id"  id="sId"
                        asp-items="@(new SelectList(@ViewBag.messageStudent,"Id", "Name"))">
                </select>
            </div>
            <div >
                <label asp-for="DeptName" >Department Name</label>
                <input asp-for="DeptName" id="dId"   type="text" placeholder="Dept Name" disabled>
            </div>

            <input type="hidden" asp-for="Id" name="Id" id="DeptName" />

        </div>

This is my controller code that is passed a list from database to View

    public async Task<IActionResult> DropDown()
    {
        var model = _scope.Resolve<FormModel>();

        await model.LoadStudenDataAsync();
        var studentList = model.StudentList.ToList();

        studentList.Insert(0, new Student { Id = 0, Name = "Select Group" });

        ViewBag.messageStudent = studentList;
        return View(model);
    }

Now I need to pass student id from view page, if i pass student id then I solve my problem, This is my JsonResult Action

    public async Task<JsonResult> GetDeptName(int studentId)
    {
        var model = _scope.Resolve<FormModel>();

        if (ModelState.IsValid)
        {
            await model.DeptList(studentId);
        }

        return Json(model);
    }

Please help me anyone how to pass student id,Thanks in Advance

CodePudding user response:

you have to use get ajax since you are not posting any data in the request body. And change data type to json since you are returning json

$.ajax({
            type:"GET", 
            url:"/Department/GetDeptName/"   studentId,
            dataType: 'json',
            ....

and action

[Route("~/Department/GetDeptName/{studentId}")]
public async Task<JsonResult> GetDeptName(int studentId)

and fix route config

public static void RegisterRoutes(RouteCollection routes)
         {
          routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
          routes.MapMvcAttributeRoutes();
          routes.MapRoute(
          name: "Default",
          url: "{controller}/{action}/{id}",
          defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
       );

but if you use old net that doesn't support attribute routing then just change ajax and leave the action as it is now

$.ajax({
            type:"GET", 
            url:"/Department/GetDeptName?studentId="   studentId,
            dataType: 'json',
            ....
  • Related