带$ .ajax的MVC无参数操作方法不返回结果

时间:2017-07-25 02:02:35

标签: jquery ajax asp.net-mvc html5 css3

我有2个下拉列表框,我将值加载到第一个下拉列表中,根据其选择,我通过ajax通过相同的操作方法将值加载到第二个

下面是我的脚本

$(document).ready(function () {       
    $("#ddlOrgs").change(function () {
    var listSite = $("#_site");
    var SelctedOrgCode = $("#ddlOrgs").val();
    alert(SelctedOrgCode);
    if (SelctedOrgCode != 0) {               

        var url = '@Url.Action("GetSites","FilterMenu")';               
        $.ajax({               
            url : url,
            type: 'POST',
            tempdata:{},
            data: JSON.stringify(tempdata),                    
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
        })
        .done(function (data) {   
        var sitesDropdown = $("#ddlSites");                                      
        var list = data;
        $.each(list, function (index, item) {
                sitesDropdown.append('<option value?+item.SiteCode+?="">' + item.SiteName + '</option>');
                alert(item);
         });

      })
      .fail(function(xhr){
           alert('failed');
           alert(xhr.responseText); 
     });
            }             
        });
    });

我的控制器操作方法

[HttpPost]
public IEnumerable<Client> LoadFiltersX(constants.ClientType clientType)
{  
         List<Client> Clients = new List<Client>();
         Client thisClient = new Client();

         _client.UserName = this.UserName;

         ClientRepository ClientRepo = new ClientRepository(_client);

         switch (clientType)
         {
             case constants.ClientType.ORG:
                 Clients = ClientRepo.GetClientInformation(constants.ClientType.ORG);
                 //HttpContext.Current.Session.Add(constants.SESSION_CLIENT,thisClient);
                 System.Web.HttpContext.Current.Session.Add(constants.SESSION_CLIENT, _client);
                 break;
             case constants.ClientType.CLIENT:
                 Clients = ClientRepo.GetClientInformation(constants.ClientType.CLIENT);
                 System.Web.HttpContext.Current.Session.Add(constants.SESSION_CLIENT, thisClient);
                 System.Web.HttpContext.Current.Session.Add(constants.SESSION_CLIENT, _client);
                 break;
             case constants.ClientType.SITE:
                 Clients = ClientRepo.GetClientInformation(constants.ClientType.SITE);
                 System.Web.HttpContext.Current.Session.Add(constants.SESSION_CLIENT, thisClient);
                 System.Web.HttpContext.Current.Session.Add(constants.SESSION_CLIENT, _client);
                 break;
             case constants.ClientType.SYSTEM:
                 Clients = ClientRepo.GetClientInformation(constants.ClientType.SYSTEM);
                 System.Web.HttpContext.Current.Session.Add(constants.SESSION_CLIENT, thisClient);
                 System.Web.HttpContext.Current.Session.Add(constants.SESSION_CLIENT, _client);
                 break;
         }
         System.Web.HttpContext.Current.Session.Add(constants.SESSION_CLIENT, _client);

         return Clients;
     }








      [HttpPost]              
         public JsonResult GetSites()
         {             
              return Json( LoadFiltersX(constants.ClientType.SITE), JsonRequestBehavior.AllowGet);

          }

在我的存储库中,我返回了List集合,如下所示

public List<Client> GetClientInformation(constants.ClientType clientType)
        {
            List<Client> Clients = new List<Client>();
            Repository Repo = new Repository();

            Paralist.Clear();
            SqlParameter p = new SqlParameter("OrgCode", _client.OrgCode);

            Paralist.Add(p);
            p = new SqlParameter("SiteCode", _client.SiteCode);
            Paralist.Add(p);

            p = new SqlParameter("ClientCode", _client.ClientCode);
            Paralist.Add(p);

            p = new SqlParameter("UserName", _client.UserName);
            Paralist.Add(p);

            try
            {
                SqlCommand com = Repo.GetCommand("uspStructureBuilderFilterGET", Paralist);
                Client AddingClient = null;
                using (IDataReader ClientReader = com.ExecuteReader())
                {
                    while (ClientReader.Read())
                    {                         
                        switch(clientType)
                        {
                            case constants.ClientType.ORG:                            
                                AddingClient = new Client(){ OrgCode=ClientReader["OrgID"].ToString(), OrgName = ClientReader["Description"].ToString() };
                                break;                           

                            case constants.ClientType.SITE:

                                AddingClient = new Client(){ OrgCode = _client.OrgCode, OrgName = _client.ClientName, SiteCode=ClientReader["SiteID"].ToString(), SiteName = ClientReader["Description"].ToString() };
                                break;

                            case constants.ClientType.CLIENT:
                                AddingClient = new Client(){ OrgCode = _client.OrgCode, OrgName = _client.ClientName, SiteCode= _client.SiteCode, SiteName = _client.SiteName, ClientCode=ClientReader["ClientID"].ToString(), ClientName = ClientReader["Description"].ToString() };
                                break;

                            case constants.ClientType.SYSTEM:
                                AddingClient = new Client(){OrgCode = _client.OrgCode, OrgName = _client.ClientName, SiteCode= _client.SiteCode, SiteName = _client.SiteName, ClientCode = _client.ClientCode, ClientName = _client.ClientName, SystemId=ClientReader["SystemID"].ToString(), SystemName = ClientReader["System"].ToString() };
                                break;
                        }
                        AddingClient.UserName = _client.UserName;                        
                        Clients.Add(AddingClient);
                    }
                }                
            }
            catch(Exception e)
            {
                ErrorLogger el = new ErrorLogger();
                el.AddErrorToLogger("ClientRepository", "GetClientInformation", e.Message, HttpContext.Current.User.Identity.Name);
                throw e;
            }

            return Clients;
        }

查看部件(位于布局文件中)

@if (Session.Count > 0 && Session["UserName"].ToString().Length > 0)
{
    Client Client = new StB.Models.Client();
    ClientRepository cr = new ClientRepository(Client);
    //FilterMenu fm = new FilterMenu(Client);
    FilterMenuController fmc = new FilterMenuController(Client);

     <div class="DrawEmptyRow"></div>


    <div class="navbar">
        @*<div class="navbar-collapse collapse">*@
        <ul class="nav navbar-nav list-inline ListItemHeight">
            <li>Org: @Html.DropDownList("ddlOrgs", new SelectList(fmc.GetAllOrganizations.ToList(), "OrgCode", "OrgName", String.Empty), "-- Select Organisation --")</li>           
            <li id="_site">Site: <select id="ddlSites" name="ddlSites">
   <option value="">Select Site </option>
</select></li>

            <li>Exclude Decom: @Html.CheckBox("exDcom")</li>
            <li>Exclude No Equip: @Html.CheckBox("ExNoEQuip")</li>
        </ul>          
    </div>        
}

当我呼叫时没有返回结果且控制台显示错误&#34; tempdata未定义&#34;。此方法不传递任何参数。每个下拉列表都有相同的客户列表,但首先需要&#39; ORG&#39;枚举和第二次使用网站&#39;枚举。所以我为每个方法传递了它。我想让List填充下拉列表。我通过Controller中的常规Action方法成功加载第一个dropdwon列表。但问题出现在ajax方法中。请帮助我,因为我被困在哪里出错了。我应该把它改成&#39; GET&#39 ;?然后ajax方法失败并显示带有css值的html页面。任何人请帮助我,因为我正在努力得到这个。感谢Advance中的任何帮助。

感谢 TPK

2 个答案:

答案 0 :(得分:0)

在你的ajax调用中删除“tempdata”变量,如果你没有任何值。

        $.ajax({               
            url : url,
            type: 'POST',                
            data: {}, // Pass the paramaters for MVC action method here...                    
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
        })

url ='@ Url.Action(“GetSites”,“FilterMenu”)'; :注意:如果您将javascript移动到单独的javascript文件,这将不起作用。使用相对网址“/ Controller / ActionMethod”。

答案 1 :(得分:0)

我使用JsonResult返回方法

找到了带有$ .getJSON的解决方案
  var url = "/FilterMenu/GetAllSites"
  $.getJSON(url, function (response) {           
            sites.empty(); // remove any existing options
            $.each(response, function (index, item) {         
                sites.append('<option value='+item.SiteCode +'>' + item.SiteName + '</option>')
            });

是的你是对的我使用了@ Url.Action方法,但当我点击链接url在浏览器中加载时返回错误说“无法找到位置404错误”,如下所示 (这是我得到的另一个问题) http://localhost:10345/ 主页 / FilterMenu / GetAllSites(注意新的新链接正在添加到Home Controller部分)

当我提供完整的网址时(如此http://localhost:10345/FilterMenu/GetAllSites并点击输入,它会跳转到正确的操作方法并返回结果。

我意识到其他/ Home部分会出错。现在我变成了相对的网址,就像你说的那样有效。事实上,我和以前一样,但都没有。但现在$ getJSON解决了问题。感谢您回复我,非常感谢。