简体   繁体   中英

Ajax action URL to a controller inside a partial view

I have a partial view which has dual list boxes and four buttons; exactly like this http://www.meadmiracle.com/dlb/DLBPlugin.aspx

Now I want to reuse this partial view all throughout the site and every time a user clicks on the buttons to move things in and out of the list, I want this to be persisted in the database via Ajax, I am making an Ajax call using JQuery; this poses a difficulty because the URL of the Ajax call will be different based on the controller that is responding to the call!

$.ajax({
        type: "POST",
        url: '@Url.Action("######HOW TO FIGRE OUT WHICH CONTROLLER #######")',
        success: function (data) {
    //Show some message to the user
        }
    });

Now how do I determine the URL? it will be dynamic, it will be based on the controller that is responding to the initial Index page.

eg: if I am in the Cities or Towns page, the user moves Cities and Towns to the list boxes, how do I know it's the CityController ajax action or the TownController ajax action, how would we know this in the partial view where to post for the ajax call?

Have your PartialView use a Model which has some properties which define the URL to be called, then the View calling the partial view passes this model, so that your AJAX knows which View to call

eg

The ViewModel

public class DualListBoxViewModel {
   public string Controller { get; set; }
   public string Action { get; set; }      
}

The Partial View

@model DualListBoxViewModel 
$.ajax({
        type: "POST",
        url: '@Url.Action(model.Controller, model.Action)',
        success: function (data) {
    //Show some message to the user
        }
    });

The View calling the PartialView

@{ Html.RenderPartial("DualListBoxWithAjax", new DualListBoxViewModel { Controller = "Town", Action = "UpdateListBox" } ); }

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