Morteza.M
Morteza.M

Reputation: 177

calling action with string type parameter from JavaScript in MVC

I have bellow action in my controller:

public ActionResult ShowContactTel(string tel)
{
    return PartialView("ContactInfoView", tel);
}

And I call above action by JavaScript like this: (It is fired by clicking on a button)

function ShowTel(){
    var e="@Model.TelShow";
    $.get("ViewProfile/ShowContactTel", e).then(
        function (r) {
            $('#divTel').innerHTML = r;
        });
}

But input argument of action receives null value (by setting break-point) and so return undesirable output.

Remark 1:

I tried bellow code for ShowTel() function but result not changed:

var str = "@Model.TelShow";
$.ajax({
    type: 'GET',
    url: '@Url.Content("~/ViewProfile/ShowContactTel")',
    data: str,
    success: function (dd) {
        $('#divTel').innerHTML = dd;
    }
});

And

var str = "@Model.TelShow";
$.ajax({
    url: "ViewProfile/ShowContactTel",
    type: 'GET',
    data: str
}).then(function (r) {
    $('#divTel').innerHTML = r;
});

I also tried type: 'POST' but it not working too.

Remark 2:

Using debugger command in ShowTel() function, I see @Model.TelShow has true value.

What is the problem?

Upvotes: 0

Views: 578

Answers (1)

Shyju
Shyju

Reputation: 218732

Your current code (first approach) is passing the value of e variable as the data parameter for the $.getcall. jQuery $.get method will send that as query string values. So your code is making a get call like the below URL.

/ViewProfile/howContactTel?testValue

Assuming testValue is the value of variable e

Your action parameter name is tel. So send an js object with a property with that name.

Also use the jquery html method to update the inner html of your div.

$.get("/ViewProfile/ShowContactTel", { tel: e })
 .then(function (r){
       $('#divTel').html(r);
  });

I would also recommend using the Url helper methods to generate the correct relative URLs to the action method.

var url = "@Url.Action("ShowContactTel","ViewProfile");
$.get(url, { tel: e }).then(function (r){
    $('#divTel').html(r);
});

Upvotes: 1

Related Questions