Search code examples
asp.net-mvc-4razor-2

Get textbox value for Ajax ActionLink in MVC 4 / Razor


I am doing a classic search field with a button. I am using Ajax.ActionLink for the button, and I cannot figure out how to get the textbox value posted in the ActionLink. I looks like this:

<div class="input-append">
    <input type="text" id="Company_CompanyName" />
    @Ajax.ActionLink("search",
                     "CompanySearch",
                      new { searchString = "???" },
                            new AjaxOptions
                            {
                                HttpMethod = "GET",
                                InsertionMode = InsertionMode.Replace,
                                UpdateTargetId = "CompanySearchResults"
                            },
                            htmlAttributes: new { @class = "btn" })
</div>

<div id="CompanySearchResults"></div>

Where the ??? is, is where I don't know how to get the value from the textbox in. What do I do?

UPDATE 1: It is a nested form

As I should have mentioned in the original post/question, this is a nested form, i.e. there is an outer form to be submitted. Therefore if I make a Ajax.BeginForm() with a submit inside it, it will invoke the submission of the outer form. I obviously want to avoid that.


Solution

  • Okay, so, I'd try making it a 'dumb' link/button and handling all the information passing by way of javascript. It would look something like the following.

    I believe there are syntax errors in the following script so only use it as a guideline.

    <input type="text" id="Company_CompanyName" />
    <a href="#" id ="CompanySearch" class="btn">Search</a>
    <div id="CompanySearchResults"></div>
    
    
    <script type="text/javascript">
    $('#CompanySearch').click(function() {
        var searchTerm = $("#Company_CompanyName").text();
        $.ajax({
            url: @Url.Action("search","CompanySearch") ,
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: {'SearchTerm' : searchTerm}  // JSON.stringify(searchTerm),
            success: function(result) {
                $('#CompanySearchResults').html(result);
            }
          });
         return false;   
    });
    </script>