简体   繁体   中英

Loading a Partial View in MVC ASP.Net using jQuery

I'm very new to both of these so please forgive my basic question.

I have an index page like:

<div id="SearchBar">              
    <%= Html.Encode("Search by Site Name: ") + Html.TextBox("SearchTextBox") %>    
    <input type="submit" value="Search" id="jQuerySubmit" />   
</div>
<div id="SiteList">   
    <% Html.RenderPartial("SiteIndexSearchResults", Model); %>                     
</div>

This all works fine.

I want to reload this partial based on what the user types in 'SearchTextBox' (I've hardcoded this in controller for now - for test purposes)

I can't get the partial to reload using:

$(document).ready(function() {
    $("#jQuerySubmit").click(function() {
        $("#SiteList").load("/Site/IndexSearch/");         
    });
});

It goes into the controller and does return the new view based on IsAjaxResult being true but does not refresh the page.

Thanks in advance.

Davy

Since #jQuerySubmit is a form submit button you need to prevent the default action which is submitting the form normally (without AJAX). To do this you need to return false from your click handler:

$(document).ready(function() { 
    $("#jQuerySubmit").click(function() {
        $("#SiteList").load("/Site/IndexSearch/");         
        return false;
    });
})

You need to stop the "normal" handling of the link click. In most browsers, this is done by letting the click handler return false , but in Firefox you can also use event.preventDefault() , like this:

$(function() { // Shorthand for the $(document).ready(function() { - does the same
    $('#jQuerySubmit').click(function(ev) { // Takes the event as a parameter
        ev.preventDefault();
        $('#siteList').load('/Site/IndexSearch/');
        return false;
    });
});

If there is a possibility that more links will be loaded with AJAX that you want to apply this behavior to, you can use .live() instead of .click() , like this:

$(function() {
    $('#jQuerySubmit').live('click', function(ev) {
        // The behavior is now applied to all links that are ever loaded on the page
        // that have the id set to jQuerySubmit.
        ...
    });
});

Thanks for the answers - both really helpful. I was returning a View instead of a PartialView in my controller (donkey).

I now have a textBox tha incrementally returns rows to my partial list based on a textbox val, which is what i was going for all along.

Thanks Again.

Davy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM