2016-12-24 1 views
0

Я изменил код представления, но он по-прежнему не заполняет фонд ddl. Кто-нибудь может понять, в чем проблема?2-й ddl неправильно заполняется


Этот код вызывает ClientInvestmentsSince2 через Json, этот метод в коде контроллера отчетов выполняется полностью. Затем, когда элемент управления возвращается в представление, я не уверен, что произойдет. Код отвечает на элемент выбора клиентов ddl и должен заполнить фонд ddl средствами, которые имеет выбранный клиент. Что-то подозрительно ... предупреждения не все стреляют после того, как я выбираю клиента. предупреждение («here2») есть, но не предупреждение («here3») или предупреждение («here4»).

Вы можете помочь? Благодарю.

**************************** вот код вида ************** *************************

@model StockHoldings.Models.Investments 

<head> 
    <script src="jquery-3.1.1.min.js"></script> 
    @*<script src="http://code.jquery.com/jquery-1.10.1.min.js" type='text/javascript'></script>*@ 
</head> 

@using (Html.BeginForm()) 
{ 
    <br /> 
    <br /> 
    <br /> 
    <br /> 
    <br /> 
    <br /> 
    <br /> 

    @Html.DropDownList("Client", ViewData["client"] as SelectList, "Select Client", new { id = "Client_ID", style = "width: 150px;" })<br /> 
    @*{ @Html.DropDownList("Fund", "Select Fund")};*@ 
     <select id="Fund" name="Fund" , style="width: 150px;"></select><br /> 
     <div class="form-group"> 
      @Html.LabelFor(model => model.PurchaseDate, htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.EditorFor(model => model.PurchaseDate, new { htmlAttributes = new { @class = "form-control" } }) 
       @Html.ValidationMessageFor(model => model.PurchaseDate, "", new { @class = "text-danger" }) 
      </div> 
     </div> 

} 

@Scripts.Render("~/bundles/jquery") 
<script type="text/jscript"> 
    $(document).ready(function() {  
     $('#Client_ID').change(function() 
     { 
      alert('here'); 

      $.getJSON('@Url.Action("ClientInvestmentsSince2", "Reports")', { id: $('#Client_ID').val() }, function (data) 
      { 
       var items = '<option>Select Fund</option>'; 
       $.each(data, function (i, Fund) 
       { 
        items += "<option value='" + Fund.i + "'>" + Fund.val + "</option>"; 
       }) 
       .fail(function (jqxhr, textStatus, errorMessage) { alert(errorMessage); }); 

       //assign the result to the Fund selectlist 
       $('#Fund').html(items); 
      }); 
      alert('here2'); 
     }); 
     alert('here3'); 
    }); 


**************** *********************** Вот код ReportController *********************** **********

using System.Collections.Generic; 
using System.Web.Mvc; 
using System.Data.SqlClient; 

namespace StockHoldings.Controllers 
{ 
    public class ReportsController : Controller 
    { 

     // GET: Reports/ClientInvestmentsSince 
     public ActionResult ClientInvestmentsSince() 
     { 
      string str = @"Data Source=USER\SQLEXPRESS;Initial Catalog=HoldingsConnectionString2;Integrated Security=True"; 
      SqlConnection con = new SqlConnection(str); 
      string query = "select ID, LastName from Clients"; 
      SqlCommand cmd = new SqlCommand(query, con); 
      con.Open(); 
      SqlDataReader rdr = cmd.ExecuteReader(); 
      List<SelectListItem> li = new List<SelectListItem>(); 
      while (rdr.Read()) 
      { 
       li.Add(new SelectListItem { Text = rdr[1].ToString(), Value = rdr[0].ToString() }); 
      } 
      ViewData["client"] = li; 

      return View(); 
     } 


     public JsonResult ClientInvestmentsSince2(int Id) 
     { 
      string str = @"Data Source=USER\SQLEXPRESS;Initial Catalog=HoldingsConnectionString2;Integrated Security=True"; 
      SqlConnection con = new SqlConnection(str); 
      string query = "select ID, Fund from Investments where Client_ID = " + Id; 
      SqlCommand cmd = new SqlCommand(query, con); 
      con.Open(); 
      SqlDataReader rdr = cmd.ExecuteReader(); 
      List<SelectListItem> li = new List<SelectListItem>(); 
      while (rdr.Read()) 
      { 
       li.Add(new SelectListItem { Text = rdr["ID"].ToString(), Value = rdr["Fund"].ToString() }); 
      } 
      ViewData["Fund"] = li; 

********************************************* 

// ViewData["Fund"] is loading correctly, and there is a clean exit of the method. 


      return Json(li, JsonRequestBehavior.AllowGet); 
     } 

} 
} 

ответ

0
 $(document).ready(function() { 
     $('#Client_ID').change(function() { 
      alert('here'); 

      $.getJSON('@Url.Action("ClientInvestmentsSince2", "Reports")', { id: $('#Client_ID').val() }, function (data) { 
       //On client DDL change you have to fill second drop down list right so after called a method it willl 
       //return json here and you can then play with that json to fill your second DDL 
      }); 
      alert('here2'); // it will fire when Client ddl change 
     }); 
     alert('here3');// it will fire once when there is page load 
     }); 
     alert('here4');//it will never fire as it's not in ready function 

Пожалуйста, найти мои комментарии на вашем сценарии были некоторые синтаксические ошибки я решил и некоторые полезные комментарии, чтобы понять, как работает эта функция, это помогает

Смежные вопросы