NealR
NealR

Reputation: 10709

jQuery/Ajax passing undefined parameter to ASP MVC controller

This should be a simple operation at the moment my program does not feel the same. When the user inputs any amount of text into a field in my view, they should be able to click on the magnifying glass which will send the text they have sent to the controller, which will in turn call a web service and perform a company name search.

Below is a function I've created that simply sends two parameters to an ASP MVC 3 controller. When I view the variable searchItem both in the Chrome debugger and in Visual Studio in the controller, I can see that it is null or undefined however the second item always comes through alright.

function GetCompDetails() {
    var searchItem = $('#DRMCompanyId').val;
    var request = $.ajax({
        type: 'POST',
        url: '@Url.Action("compSearch", "AgentTransmission")',
        data:
            {
                searchFilter: searchItem,
                url: location.protocol + '//' + location.host
            },
        dataType: 'html',
        success: function (data) {
            alert(data);
        },
        error: function (data) {
            alert("Unable to process your resquest at this time.");
        }
    });
}

Here is the <div> I'm using that should be passing the searchItem parameter. As you can see I've tried two different method of creating the text box/input area. Both, however, wind up passing the parameter as being undefined.

Any help would be greatly appreciated.

    <div class="M-editor-field">
        <img src="@Url.Content("~/Content/Images/magnify.gif")" onclick="GetCompDetails()" />
        @Html.TextBoxFor(model => model.BankName, new { id = "DRMCompanyId" })
        @*@Html.EditorFor(model => model.DRMCompanyId)*@
        @Html.ValidationMessageFor(model => model.DRMCompanyId)
    </div>

Here is the method signature from my controller. searchFilter is currently undefined each time however the url paramter works fine.

    [HttpPost]
    public string compSearch(string searchFilter, string url)
    {

Upvotes: 0

Views: 1782

Answers (1)

Kenneth
Kenneth

Reputation: 28737

You have an error in your Javascript, in your first line you forget the pernthesis

function GetCompDetails() {
    var searchItem = $('#DRMCompanyId').val();    // You need to add parenthesis if you call a function
    var request = $.ajax({
        type: 'POST',
        url: '@Url.Action("compSearch", "AgentTransmission")',
        data:
            {
                searchFilter: searchItem,
                url: location.protocol + '//' + location.host
            },
        dataType: 'html',
        success: function (data) {
            alert(data);
        },
        error: function (data) {
            alert("Unable to process your resquest at this time.");
        }
    });
}

Upvotes: 1

Related Questions