最近剛接觸.net不到一個月
最近在做一個小題目
鄉鎮市的下拉選單選完後
會呈現口罩地圖的資料(就是全台縣市藥局口罩剩餘數)
以上兩個都是用政府的開放API(是不同的)
但我之前寫出來的是用區去過濾出我要的資料
(controller)
public class GetareaController : Controller
{
public async Task<ActionResult> Index()
{
var b = new GetCollection();
var areasource = await b.GetInserchdata();
ViewBag.AllCity = areasource.Select(s => s.City).Distinct().Select(item => new SelectListItem()
{
Text = item,
Value = item
});
var masksource = await b.GetMaskmapdata();
return View();
}
[HttpPost]
public async Task<JsonResult> GetSecondDDL(string cityName)
{
var CitySlectList = this.GetSelectList(await GetCity(), cityName);
if (string.IsNullOrEmpty(cityName))
{
return Json(new EmptyResult());
}
var AreaSlectList = await this.GetArea(cityName);
return Json(AreaSlectList);
}
[HttpPost]
public async Task<JsonResult> GetMaskmap(string cityName, string areaName)
{
var b = new GetCollection();
var source = GetCollection.maskdata;
//var SelectList = await this.GetArea(cityName);
var aa = source.FindAll(x => x.醫事機構地址.Contains("基隆市"));
var Maskdata = aa.FindAll(x => x.醫事機構地址.Contains(areaName)).AsEnumerable();
if (string.IsNullOrEmpty(areaName))
{
return Json(new EmptyResult());
}
return Json(Maskdata);
}
public IEnumerable<SelectListItem> GetSelectList(IEnumerable<string> source,
string selectedItem)
{
var selectList = source.Select(item => new SelectListItem()
{
Text = item,
Value = item.ToString(),
Selected = !string.IsNullOrWhiteSpace(selectedItem)
&& item.Equals(selectedItem, StringComparison.OrdinalIgnoreCase)
});
return selectList;
}
public async Task<List<string>> GetCity()
{
var b = new GetCollection();
var citysource = await b.GetInserchdata();
if (citysource != null)
{
var country = citysource.Select(x => x.City)
.Distinct();
return country.ToList();
}
return new List<string>();
}
public async Task<List<string>> GetArea(string cityName)
{
var b = new GetCollection();
var areasource = await b.GetInserchdata();
if (areasource != null)
{
var district = areasource.Where(x => x.City == cityName).Select(x => x.Area)
.Distinct();
return district.ToList();
}
return new List<string>();
}
後來才發現不同的縣市會有重複的區名
我想知道我大概要怎麼改比較好呢
我目前 public JsonResult GetMaskmap(string cityName, string areaName)
{
var b = new GetCollection();
var source = GetCollection.maskdata;
//var SelectList = await this.GetArea(cityName);
var aa = source.FindAll(match: x => x.醫事機構地址.Contains(cityName)); (((這裡會是null
但areaName是可以抓到值的
(除非在裡面直接contain縣市的名稱 如內容裡"基隆市")
我想說是否可以直接在ajax裡面多加CITY 的value參數
但好像也沒辦法
希望各位前輩不吝嗇指教
(model 兩個api都在這裡抓)
public class Inserch
{
[Display(Name = "縣市")]
public string City { get; set; }
[Display(Name = "鄉鎮")]
public string Area { get; set; }
public string 醫事機構代碼 { get; set; }
public string 醫事機構名稱 { get; set; }
public string 醫事機構地址 { get; set; }
public string 醫事機構電話 { get; set; }
public string 成人口罩剩餘數 { get; set; }
public string 兒童口罩剩餘數 { get; set; }
}
public class GetCollection
{
public static List<Inserch> collection;
public static List<Inserch> maskdata;
public async Task<IEnumerable<Inserch>> GetInserchdata()
{
string cacheName = "Area_Inserches";
ObjectCache cache = MemoryCache.Default;
CacheItem cacheContents = cache.GetCacheItem(cacheName);
if (cacheContents == null)
{
return await RetriveInserchdata(cacheName);
}
else
{
return cacheContents.Value as IEnumerable<Inserch>;
}
}
public async Task<IEnumerable<Inserch>> RetriveInserchdata(string cacheName)
{
string targetURI = "https://quality.data.gov.tw/dq_download_json.php?nid=5948&md5_url=b7ce2082883f6b680810828799d4c32e";
HttpClient client = new HttpClient();
var response = await client.GetStringAsync(targetURI);
collection = JsonConvert.DeserializeObject<List<Inserch>>(response);
CacheItemPolicy policy = new CacheItemPolicy();
policy.AbsoluteExpiration = DateTime.Now.AddMinutes(30);
ObjectCache cacheItem = MemoryCache.Default;
cacheItem.Add(cacheName, collection, policy);
return collection;
}
public async Task<IEnumerable<Inserch>> GetMaskmapdata()
{
string targetURI = "https://quality.data.gov.tw/dq_download_json.php?nid=116285&md5_url=53a72b2dcfdd9ecae43afda4b86089be";
HttpClient client = new HttpClient();
client.MaxResponseContentBufferSize = Int32.MaxValue;
var response = await client.GetStringAsync(targetURI);
//ViewBag.Result = Regex.Unescape(response);
maskdata = JsonConvert.DeserializeObject<List<Inserch>>(response);
return maskdata;
}
}
}
(view)
@using Test.Models
@model IEnumerable<Test.Models.Inserch>
@{
ViewBag.Title = "Index";
var data = ViewBag.allData;
}
@section scripts {
<script type="text/javascript">
$(document).ready(function () {
$("#CITY").change(function () { ChangeCity(); });
$("#AREA").change(function () { ChangeArea(); });
$(document).on('submit', '#ButtonSubmit', function () {
return false;
});
});
function SetareaEmpty() {
$('#CITY').empty();
$('#CITY').append($('<option></option>').val('').text('請選擇'));
}
function ChangeCity() {
var selectedCity = $.trim($('#CITY option:selected').val());
if ($.trim(selectedCity.length) > 0) {
ChangeArea(selectedCity);
}
else {
SetareaEmpty()
}
}
function ChangeArea(selectedCity) {
$.ajax({
type: "POST",
url: '@Url.Action("GetSecondDDL", "Getarea")',
dataType: "json",
data: { cityName: selectedCity },
success: function (mems) {
if (mems.length > 0) {
$('#AREA').empty();
$('#AREA').append($('<option></option>').val('').text('請選擇'));
}
$.each(mems, function (i, member) {
$("#AREA").append($('<option></option>').val(member).text(member));
});
}
});
}
function SerchallData(selectedCity) {
var selectedValue = $('#AREA option:selected').val();
if ($.trim(selectedValue).length > 0) {
$.ajax({
url: '@Url.Action("GetMaskmap", "Getarea")',
data: { cityName: selectedCity, areaName: selectedValue },
type: 'POST',
dataType: 'json',
success: function (data) {
$('#MASK').empty;
for (var i = 0; i < data.length; i++) {
var row = $('<tr><td>' + data[i].醫事機構代碼 + '</td><td>' + data[i].醫事機構名稱 + '</td><td>' + data[i].醫事機構地址 + '</td></tr>' + '<tr><td>' + data[i].醫事機構電話 + '</td><td>' + '<tr><td>' + data[i].成人口罩剩餘數 + '</td><td>' + '<tr><td>' + data[i].兒童口罩剩餘數 + '</td><td>');
$('#MASK').append(row);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error: ' + textStatus + ' - ' + errorThrown);
}
});
}
}
</script>
}
<div class="row well">
<form>
<div class="col-lg-3">
<div class="input-group">
<span class="input-group-addon">縣市</span>
<p>
@Html.DropDownList("City", (IEnumerable<SelectListItem>)ViewBag.Allcity, "請選擇", new { id = "CITY" })
</p>
</div>
</div>
<div class="col-lg-3">
<div class="input-group">
<span class="input-group-addon">鄉鎮</span>
<p> <select id="AREA" name="AREA"><option>請選擇</option></select></p>
</div>
</div>
</form>
<div class="col-lg-2">
<button type="submit" onclick="SerchallData()" id="ButtonSubmit" class="btn btn-primary">
<span class="glyphicon glyphicon-search"></span>查詢
</button>
</div>
</div>
<table id="MASK">
<tr>
<th>醫事機構代碼</th>
<th>醫事機構名稱</th>
<th>醫事機構地址</th>
<th>醫事機構電話</th>
<th>成人口罩剩餘數</th>
<th>兒童口罩剩餘數</th>
</tr>
</table>
因為你button呼叫時沒餵縣市參數給function SerchallData(selectedCity),selectedCity為undefined,改成以下就正常了
function SerchallData() {
var selectedCity = $('#CITY option:selected').val();//新增讀取縣市
var selectedValue = $('#AREA option:selected').val();
if ($.trim(selectedValue).length > 0) {
...
});
}
}