Anders
Anders

Reputation: 1042

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.

Upvotes: 2

Views: 11639

Answers (2)

monkeyhouse
monkeyhouse

Reputation: 2896

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>

Upvotes: 3

monkeyhouse
monkeyhouse

Reputation: 2896

This answer is moot b/c the link is wihin a form, I'll try to make another answer in a bit...

Use an ajax form for this - not a link. You need a form to include values in the postback, ie.

@using (Ajax.BeginForm("search", "CompanySearch",new AjaxOptions { HttpMethod = "GET", InsertionMode =      InsertionMode.Replace, UpdateTargetId = "SearchResults" }))
{    
<h1>Search</h1>
<input type="text" placeholder="Search Terms" name="SearchTerms"/>
 <input type="submit" name="Command" value="Search" />
}


<div id="SearchResults"></div>

Upvotes: 3

Related Questions