Get textbox value for Ajax ActionLink in MVC 4 / Razor

﹥>﹥吖頭↗ 提交于 2019-12-24 01:40:47

问题


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.


回答1:


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>



回答2:


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>


来源:https://stackoverflow.com/questions/15587733/get-textbox-value-for-ajax-actionlink-in-mvc-4-razor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!