Kamaal Shaik
Kamaal Shaik

Reputation: 77

Unable to call a controller action method using Ajax

I am beginner to jquery-ajax. I trying to get Employee data into front-end using ajax method. But the url is not calling the action method. Please check the below code

MyScripts.js:

function fn_test()
{
    var eno = $("#t1").val();

    $.ajax({
        cache :false,
        url: "Home/GetEmpData/"+eno,
        type: 'GET',
        data:"",
        contentType:'application/json;',
        success: function (response)
        {
            var str = "Ename :" + response.EmpName + "<br >";
            str += "Job :" + response.Job + "<br >";
            tr += "Salary :" + response.Salary + "<br >";
            str += "Deptno :"+response.DeptNo+"<br >";
            $("#sp1").html(str);
        }
    });
}

Action method in HomeController.cs

public ActionResult GetEmpData(int id)
{
    Employee obj = db.Employees.Find(id);
    return Json(obj, JsonRequestBehavior.AllowGet);
}

Index.cshtml

Enter your name :
<input type="text" id="t1" /><br /><br />
<input type="button" id="b1" onclick="fn_test()" value="get message" /><br /><br />
<span id="sp1"></span>

Please help me.

Upvotes: 0

Views: 1490

Answers (2)

Muhammad Nasir
Muhammad Nasir

Reputation: 2204

you are passing parameter as query string .you have tell the browser this using ? sign before variable name that you had used in controller and after this you can assign value to this.

function fn_test()
    {
        var eno = $("#t1").val();

        $.ajax({
            cache :false,
            url: "Home/GetEmpData?parameterNameInController="+eno,
            type: 'GET',
            data:"",
            contentType:'application/json;',
            success: function (response)
            {
                var str = "Ename :" + response.EmpName + "<br >";
                str += "Job :" + response.Job + "<br >";
                tr += "Salary :" + response.Salary + "<br >";
                str += "Deptno :"+response.DeptNo+"<br >";
                $("#sp1").html(str);
            }
        });
    }


public ActionResult GetEmpData(int id)
{
Employee obj ;
try{
    obj = db.Employees.Find(id);
    return Json(obj, JsonRequestBehavior.AllowGet);
}catch(Exception ex)
{ obj=new Employee();
//return empty object
return Json(obj, JsonRequestBehavior.AllowGet);
}
}

Upvotes: 0

user3559349
user3559349

Reputation:

Construct you urls correctly using

url: '@Url.Action("GetEmpData", "Home")',

and pas the data using

data: { id: eno },

and remove

contentType:'application/json;',

Edit

Since your script is in a separate file, modify your html to

<input type="button" id="b1" data-url="@Url.Action("GetEmpData", "Home")" value="get message" />

Then change the script to

$('#b1').click(function() {
  $.ajax({
    cache :false,
    url: $(this).data('url'),
    type: 'GET',
    data: { id: $("#t1").val() },
    success: function (response) {
     ...
    }
  });
});

Upvotes: 1

Related Questions