user2718165
user2718165

Reputation: 215

Call MVC4 partial view with Jquery Ajax

I need you help with my mvc4 project. I have 2 drop down menus. When i select firs one, the second is automatically populated with help of Jquery and Ajax. When i select the other one, which is now populated with some data, i need to invoke a method which calls a PL/SQL procedure, and i need to pass a value to that method, which is selected in a second drop down menu. That method returs some data which I need to pass to my partial view and in that partial view i need to generate a tree view from passed data. So far i was able to generate TreeView (using jsTree) in my partial view when i hardcoded a value and invoked my method from controler, but i need to do that when i select a value from my second drop down list.

This is my code:

My Controller

    public class IndexController : Controller
{

    public ActionResult Index()
    {
        EpfeSelectScreen model = new EpfeSelectScreen();

        #region Country

        var b = (from a in dbEntitiesErste.CONFIG_COUNTRIES
                 orderby a.COUNTRY_ID
                 select new Countries
                 {
                     Text = a.COUNTRY_NAME,
                     Value = a.COUNTRY_ID
                 });

        model.Country = b.OrderBy(x => x.Text).ToList();
        #endregion

        #region Oracle Stored Procedures

        List<TreeNode> list = new List<TreeNode>();
        list = ClassData.GetAllClasses(1); //hardcoded value 1 Here goes the value from second drop down list
        var TopHierarchy = list.Where(x => x.ParentId == -1).FirstOrDefault();
        SetChildren(TopHierarchy, list);

        #endregion

        var pmViewModel = new MainViewModel
        {
            FullModelObject = model,
            PartialModelObject = TopHierarchy
        };

        return View(pmViewModel);


    }

    #region generate Tree
    private void SetChildren(TreeNode model, List<TreeNode> list)
    {
        var childs = list.Where(x => x.ParentId == model.ChildId).ToList();
        if (childs.Count > 0)
        {
            foreach (var child in childs)
            {
                SetChildren(child, list);
                model.Children.Add(child);

            }
        }

    }
    #endregion


    #region jquery methods

    [OutputCache(Duration = 0)]
    [HttpGet]
    public JsonResult Application(string[] Country)
    {
        var apl = new List<Applications>();
        if (Country[0] == "")
        {
            //*aplications
            var result = (from a in dbEntitiesErste.CONFIG_APPLICATIONS
                             select new Applications
                             {
                                 Text = a.APPLICATION_NAME,
                                 Value = a.APPLICATION_ID
                             });//*.OrderBy(x => x.Text).ToList()

            apl.Add(new Applications { Value = 0, Text = "--Please choose application--" });
            apl.AddRange(result.OrderBy(x => x.Text).ToList());
        }
        else
        {
            var result = (from a in dbEntitiesErste.CONFIG_APPLICATIONS
                             where Country.Contains(a.COUNTRY_ID)
                             select new Applications
                             {
                                 Text = a.APPLICATION_NAME,
                                 Value = a.APPLICATION_ID
                             }); //*.OrderBy(x => x.Text).ToList();
            apl.Add(new Applications { Value = 0, Text = "--Please choose application--" });
            apl.AddRange(result.OrderBy(x => x.Text).ToList());
        }

        var retVal = new { Application = aplikacije };
        return Json(retVal, JsonRequestBehavior.AllowGet);
    }

    //[OutputCache(Duration = 0)]
    //[HttpGet]
    //public JsonResult Tree(int idApp)
    //{
    //    var ret = (from a in dbEntitiesErste.CONFIG_APPLICATIONS
    //               select new Applications
    //               {
    //                   Text = a.APPLICATION_NAME,
    //                   Value = a.APPLICATION_ID
    //               }).OrderBy(x => x.Text).ToList();

    //    return Json(ret, JsonRequestBehavior.AllowGet);
    //}


    #endregion
}

this is my main View (Index.cshtml)

@model EPFE.Models.ViewModels.MainViewModel


<!DOCTYPE html>
@{
     ViewBag.Title = "EB";    
 }
<head>
<title>EBB</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<script src="@Url.Content("~/Scripts/jquery-ui-1.10.3.js")" type="text/javascript"></script>
<script src="~/Scripts/Selections.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="@Url.Content("~/Scripts/jstree.js")" type="text/javascript"></script>
<link href="@Url.Content("~/Content/Selection.css")" rel="stylesheet" type="text/css" />
<link href="~/Content/Site.css" rel="stylesheet" />
<link href="@Url.Content("~/Content/themes/style.css")" rel="stylesheet" />
<script type="text/javascript">
    var pathAplications = '@Url.Action("Application", "Index")';
    var pathTreeView = '@Url.Action("Tree", "Index")';
</script>

</head>

<body>
     <table>
       <tr>
         <td>
           @Html.DropDownList("Country", new SelectList(Model.FullModelObject.Country, "Value", "Text"), "--Please select Country--")
         </td>
       </tr>
       <tr>
        <td>
          @Html.DropDownList("Application", new SelectList(Model.FullModelObject.Application, "Value", "Text"), "--Please choose application--")
         </td>
       </tr>
     </table>
     <fieldset class="Tree">
       <div id="divtree">
          <ul id="tree">
            <li>
               <a href="#" class="usr">@Model.PartialModelObject.ObjectIdentifier</a>
                    @Html.Partial("_TreeView", Model.PartialModelObject)
            </li>
          </ul>
       </div>
     </fieldset>
  </body>

This is my partial view (_TreeView.cshtml)

@model EPFE.TreeViewModel.TreeNode


@foreach (var item in Model.Children)
{
<ul>
    @if (item != null)
    {
        <li>
            <a href="#" class="usr">@item.ObjectIdentifier</a>
            @if (item.Children.Count > 0)
            {
                @Html.Partial("_TreeView", item)
            }

        </li>
    }

</ul>
}

and these are my models

    public class EpfeSelectScreen
{
    public string Search { get; set; }
    public string selectedApplication { get; set; }
    public string selectedCountry { get; set; }
    public string selectedMetaData { get; set; }
    public string selectedTreeView { get; set; }
    public List<Countries> Country { get; set; }
    public List<Applications> Application { get; set; }
    public List<SelectListItem> MetaData { get; set; }
    public List<SelectListItem> References { get; set; }
    public List<SelectListItem> ReferencedBy { get; set; }
    public List<SelectListItem> TreeView { get; set; }

    public EpfeSelectScreen()
    {
        Country = new List<Countries>();
        Application = new List<Applications>();
        References = new List<SelectListItem>();
        ReferencedBy = new List<SelectListItem>();
        TreeView = new List<SelectListItem>();
        MetaData = new List<SelectListItem>();
    }
}

Second one

public class MainViewModel
{
    public EpfeSelectScreen FullModelObject { get; set; }
    public TreeNode PartialModelObject { get; set; }

    public MainViewModel()
    {
        FullModelObject = new EpfeSelectScreen();
        PartialModelObject = new TreeNode();
    }
}

and the last one

public class TreeNode
{
    public int ParentId { get; set; }
    public int ChildId { get; set; }
    public int ObjectRelId { get; set; }
    public string ObjectIdentifier { get; set; }
    public string ObjectTypeId { get; set; }
    public IList<TreeNode> Children { get; set; }

    public TreeNode()
    {
        Children = new List<TreeNode>();
    }

}

and these are my scripst

$(document).ready(function () {
$("#Country").on('change', CountryChange);
//$("#selectedApplication").on('change', ApplicationChange);
//*
$("#Application").on('change', ApplicationChange);
});


function CountryChange() {

var CountryIds = [];
$("#Country option:selected").each(function (i, selected) {
    CountryIds[i] = $(selected).val();
});

$.ajax({
    url: pathAplications,
    type: 'GET',
    data: { Country: CountryIds },
    success: function (data) {
        var apl = $("#Application");

        apl.empty();

        for (var j = 0; j < data.Application.length; j++) {
            var item = data.Application[j];
            var option = "<option value='" + item.Value + "'>" + item.Text + "</option>";
            apl.append(option);
        }

    },
    error: function (x, y) {
        $("#displayError").html(x.val());

    },
    traditional: true
});
}


function ApplicationChange() {

var applicationId = [];
$("#Application option:selected").each(function (i, selected) {
    applicationId[i] = $(selected).val();
});

$.ajax({
    url: pathTreeView,
    type: 'GET',
    data: { Application: applicationId },
    success: function (data) {
        var tree = $("#selectedApplication");

        trees.empty();

        for (var j = 0; j < data.Application.length; j++) {
            var item = data.Application[j];
            var option = "<option value='" + item.Value + "'>" + item.Text + "</option>";
            trees.append(option);
        }

    },
    error: function (x, y) {
        $("#displayError").html(x.val());

    },
    traditional: true
});
}

The function ApplicationChange catches the right value but i don't know how to use it to invoke my method for pl/sql procedure and return that data to partial view.

Upvotes: 1

Views: 4441

Answers (1)

give your url like this

'@Url.Action("actionname","controllerNmae")',

also make sure if you are making a get or post request then the target action should have that attribute as well.

also you data type will be json for this.

or even better use like this

 $.getJSON('@Url.Action("Controller Name here")',
 function ()
 {          
 });

Upvotes: 1

Related Questions