2017-04-18 28 views
-1

我很新的JavaScript,jQuery和AJAX。所以我有一個模型:如何從asp.net Mvc中的層疊列表中存儲文本值元素?

namespace hiophop.Models 
{ 
    public class CarMake 
    { 
     public class Category 
     { 
      public int CategoryID { get; set; } 
      public string CategoryName { get; set; } 

     } 

     public class Product 
     { 
      public int ProductID { get; set; } 
      public string ProductName { get; set; } 
      public int CategoryID { get; set; } 
     } 
    } 
} 

我創建的類的列表,並加入到他們在我的控制,同時通過JSON的觀點:

namespace hiophop.Controllers 
{ 
    public class CarController : Controller 
    { 
     List<Category> lstCat = new List<Category>() 
     { 
      new Category() { CategoryID = 1, CategoryName = "Dairy" }, 
      new Category() { CategoryID = 2, CategoryName = "Meat" }, 
      new Category() { CategoryID = 3, CategoryName = "Vegetable" } 
     }; 

     List<Product> lstProd = new List<Product>() 
     { 
      new Product() { ProductID = 1, ProductName = "Cheese", CategoryID = 1 }, 
      new Product() { ProductID = 2, ProductName = "Milk", CategoryID = 1 }, 
      new Product() { ProductID = 3, ProductName = "Yogurt", CategoryID = 1 }, 
      new Product() { ProductID = 4, ProductName = "Beef", CategoryID = 2 }, 
      new Product() { ProductID = 5, ProductName = "Lamb", CategoryID = 2 }, 
      new Product() { ProductID = 6, ProductName = "Pork", CategoryID = 2 }, 
      new Product() { ProductID = 7, ProductName = "Broccoli", CategoryID = 3 }, 
      new Product() { ProductID = 8, ProductName = "Cabbage", CategoryID = 3 }, 
      new Product() { ProductID = 9, ProductName = "Pepper", CategoryID = 3 } 
     }; 

     public ActionResult GetCategories() 
     { 
      return Json(lstCat, JsonRequestBehavior.AllowGet); 

     } 

     public ActionResult GetProducts(int intCatID) 
     { 

      var products = lstProd.Where(p => p.CategoryID == intCatID); 
      return Json(products, JsonRequestBehavior.AllowGet); 

     } 
     [HttpGet] 
     public ActionResult Index() 
     { 

      return View(); 
     } 

     [HttpPost] 
     public ActionResult Index(string c ,string p) 
     { 


      ViewBag.x ="Product:"+ p; 
      ViewBag.y = "category" + c; 
      return View(); 
     } 

    } 
} 

這裏是被它被混淆我如何檢索所選列表框的文本值我只能檢索CategoryId的Int索引。我希望CategoryName ProductName都是字符串。這裏是我的觀點:viewbags.x和y只返回Ids。我已經嘗試了幾件事,但我陷入了困境中,我做錯了什麼?我留下了一些評論,讓你看看我在嘗試什麼。

@model hiophop.Models.CarMake 
@{ 
    ViewBag.Title = "CarView"; 
    Layout = "~/Views/Shared/_Layout.cshtml"; 
} 

@*<h2>CarView</h2>*@ 


@ViewBag.y 
@ViewBag.x 


@using (Html.BeginForm("Index", "Car", FormMethod.Post)) 
{ 
    <div> 
     <label for="category">Category</label> 
     <select id="category" name="c" class="form-control"></select> 
     <label for="product">Product</label> 
     <select id="product" name="p" class="form-control"></select> 

     <div id="result"></div> 

     <input type="submit" id="Button1" class="btn btn-default" /> 




    </div> 
} 
@section scripts { 
    <script type="text/javascript"> 
     $(document).ready(function() { 
      // Get a list of categories and a list of products of the first category. 
      $.getJSON('/Car/GetCategories', null, function (data) { 
       $.each(data, function() { 
        $('#category').append('<option value=' + 
         this.CategoryID + '>' + this.CategoryName + '</option>'); 
       }); 
       $.getJSON('/Car/GetProducts', { intCatID: $('#category').val() }, function (data) { 
        $.each(data, function() { 
         $('#product').append('<option value=' + 
          this.ProductID + '>' + this.ProductName + '</option>'); 

        }); 
       }).fail(function (jqXHR, textStatus, errorThrown) { 
        alert('Error getting products!'); 
       }); 
      }).fail(function (jqXHR, textStatus, errorThrown) { 
       alert('Error getting categories!'); 
      }); 

      // Dropdown list change event. 
      $('#category').change(function() { 
       $('#product option').remove(); 
       $.getJSON('/Car/GetProducts', { intCatID: $('#category').val() }, function (data) { 
        $.each(data, function() { 
         $('#product').append('<option value=' + 
          this.ProductID + '>' + this.ProductName + '</option>'); 
        }); 
       }).fail(function (jqXHR, textStatus, errorThrown) { 
        alert('Error getting products!'); 
       }); 
      }); 
     }); 




     //var result = $('#result'); 


     //$(document).ready(function() { 
     $("#Button").click(function() { 
      var request = $('#category option:selected').text() + "," + $('#product option:selected').text(); 
       $.ajax({ 
        type: 'POST', 
        contentType: "application/json;charset=utf-8", 
        url: '/Car/Index', 
          //data: "{'Category':'" + document.getElementById('#category') + "','food':'" + document.getElementById('#product') + " '}", 
        //  async: false, 
        //  success: function (response) { 
        //   $('#category').val(''); 
        //   $('#product').val(''); 

        //   alert("record has been saved in database"); 

        //  }, 
        //  error: function() { 
        //   console.log('there is some error'); 
        //  } 

        data: { c: request }, 
        dataType: 'json', 
        success: function (data) { 
         result.html('#category: ' + data.CategoryName + '' + '#product' + data.ProductName) 
        } 

      }); 

      }); 

     //}); 
    </script> 
} 
+0

你的代碼真的沒有意義,它不清楚你想做什麼。如果你想回發每個選擇的選項的文本,那麼它的'data:{c:$('#category option:selected')。text(),p:$('#product option:selected')。text ); }'。但是你指定你在ajax調用中返回'json',所以你的'Index()'post方法會拋出一個異常,因爲你的返回html –

+0

也建議你研究[DotNetFiddle]中的代碼(https:// dotnetfiddle。 net/1bPZym)瞭解如何實現級聯下拉列表 –

回答

0

編輯:其實,當我看你的代碼更多,和你對問題的描述,我認爲你的問題更早。即使點擊按鈕也不會觸發,因爲ID應該是Button1而不是Button,但由於您的按鈕是input type = submit,並且您使用Html.BeginForm()創建了表單,所以表單仍然在提交。這會導致表單被提交給默認的動作(與get相同,但是作爲一個帖子,而不是......這就是爲什麼它仍然會觸發正確的動作),但提交的變量只是表單中輸入的值。爲了按照你想要的方式工作,你需要改變按鈕的點擊事件(首先讓ID匹配,否則它永遠不會觸發),然後在開始的時候正確地阻止正常的表單提交。因此,它應該是這樣的:

$('#Button1').click(function(event) { 
    event.preventDefault(); 

    // Do the rest of the click event handler here 
}); 

末編輯


你已經讓你的jQuery正確的值:

$('#category option:selected').text() 

會得到了#所選文本類別下拉,而不是價值。你的問題是,你正在構建一個字符串的jquery對象,並將其作爲單個參數傳遞回來。相反,試試這個:

var postData = { 
    c: $('#category option:selected').text(), 
    p: $('#product option:selected').text() 
}; 

然後,在你的Ajax請求:

data: postData 

而且,它的價值,有這種類型的Ajax請求的一個更簡單的速記:

$.post('/Car/Index', postData).done(function(data) { 
    //Do something with the server response here 
    result.html('#category: ' + data.CategoryName + '' + '#product' + data.ProductName) 
}); 

請注意,成功,錯誤和完整回調已被棄用,並分別由done(),fail()和always()取代。

編輯地址註釋:

我先回答你的最後一個問題......是的!在瀏覽器中(大多數現代瀏覽器都有這個版本)按f12鍵。這應該打開某種開發人員工具窗口。尋找一個與JavaScript的東西在它的標籤...在Firefox中,該標籤被稱爲調試器,在鉻它被稱爲來源。我認爲它也被稱爲IE中的調試器,但我不記得。無論如何,在這個選項卡上,找到帶有JavaScript代碼的頁面(如果全部內聯,這就是您的示例所具有的內容,它將是與您的控制器操作相同的頁面,不包含擴展名)。這應該調出頁面的'查看源'版本。你可以在這裏設置javascript的斷點,當瀏覽器到達它們時,它會中斷,你可以一步一步完成,或者就像你在服務器端調試一樣。你也可以設置一個手錶,並監視變量的值。

要將數據發送到您的文章中的瀏覽器,您希望發送一個包含數據的JSON對象。 JSON實際上只是一系列鍵/值對。因此,一個JSON對象如下所示:

{ "key":"value" } 

這是一個非常簡單的JSON對象。如果我存儲在一個變量(例如POSTDATA),像這樣:

var postData = { "key":"value" }; 

我可以說postData.key訪問的「鑰匙」的價值,這將讓我的「價值」。爲了將數據發送到您的控制器操作,您需要構建一個JSON對象,該對象的屬性與控制器操作需要的參數相匹配。在你的例子中,你的POST控制器動作有兩個屬性:(string c,string p),所以你傳入的JSON對象需要一個名爲c的屬性(或KEY),一個名爲p。請記住,javascript和c#都區分大小寫,因此您的JSON對象中的屬性需要完全匹配控制器操作所需的參數名稱。

所以,你的控制器動作需要一個JSON對象,它看起來是這樣的:

{ "c":"some value", "p":"some other value" } 

注意我們的屬性用逗號分隔..你可以將任意數量在這裏。如果您的控制器操作具有可選參數,則可以將其忽略,但如果不是,則需要在這裏指定它們,否則您將收到404錯誤。因此,上面的對象正是您的控制器想要看到的內容,但這些值顯然不正確,我們需要從您的選擇列表中獲取這些值。因此,要做到這一點,我們使用您已經有了jQuery的,爲了從所選選項的文本,我們離開了這一點:

var postData = { 
    c: $('#category option:selected').text(), 
    p: $('#product option:selected').text() 
}; 

注意,指定鍵的名稱時,如果它不沒有空間或任何奇怪的東西,我們可以省略引號。

所以現在我們有一個格式正確的JSON對象,它匹配你的控制器動作想要接收的東西。我們只需要發送一個ajax文章。使用原來的帖子類型,如下所示:

$.ajax({ 
    type: 'POST', 
    //contentType: "application/json;charset=utf-8", This line is not necessary, the browser will figure it out 
    url: '/Car/Index', 
    data: postData, 
    //dataType: 'json', (This line is not necessary, the browser will figure it out 
    success: function (data) { 
     result.html('#category: ' + data.CategoryName + '' + '#product' + data.ProductName) 
    } 
}); 

請注意,有幾行註釋。對於這種類型的調用,它們不是必需的,瀏覽器很擅長弄清楚需要什麼。

另外,我更喜歡指定的帖子是這樣,這是我上面提到的簡寫方式,但我會再次把它放在這裏:

$.post('/Car/Index', postData).done(function(data) { 
    result.html('#category: ' + data.CategoryName + '' + '#product' + data.ProductName) 
}); 

這不完全一樣的東西是$就版本以上,但在我看來,這要簡單得多。

我希望清除它!我很樂意回答任何問題,或提供任何額外的說明。

+0

謝謝我對如何將數據傳遞給控制器​​發佈後感到困惑。謝謝你的迴應,這對我有很大的幫助。它不工作,因爲我想壽。我會更多地研究你的代碼。有沒有辦法來調試Ajax或查看數據是否被傳遞? –

+0

非常歡迎。我對你的問題的回答太長,以至於無法發表評論,所以我會編輯我的回答來解決它們。 – Redit0

相關問題