次のモデルの WebAPI があります。
public class Dog
{
public string name { get; set; }
public string breed { get; set; }
public string size { get; set; }
public CoatType coatType { get; set; }
private List<Dog> dogs;
}
public enum CoatType
{
Long,
Short,
Curly
};
私のリポジトリは次のようになります。
public class AnimalRepository
{
private const string CacheKey = "AnimalStore";
public AnimalRepository()
{
var context = HttpContext.Current;
if (context != null)
{
if (context.Cache[CacheKey] == null)
{
var contacts = new Dog[]
{
new Dog { name = "Lassie", breed = "Collie", size = "Medium", coatType = CoatType.Long },
new Dog { name = "Fido", breed = "Labrador", size = "Large" , coatType = CoatType.Short},
};
context.Cache[CacheKey] = contacts;
}
}
}
public Dog[] GetAllAnimals()
{
var context = HttpContext.Current;
if (context != null)
{
return (Dog[])context.Cache[CacheKey];
}
return new Dog[]
{
new Dog
{
name = "",
breed = "Placeholder",
size = "Placeholder",
coatType = CoatType.Curly
}
};
}
public bool SaveAnimal(Dog animal)
{
var context = HttpContext.Current;
if (context != null)
{
try
{
var currentData = ((Dog[])context.Cache[CacheKey]).ToList();
bool nameExists = false;
if (nameExists != true)
{
currentData.Add(animal);
context.Cache[CacheKey] = currentData.ToArray();
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return false;
}
}
return false;
}
}
そして、私のコントローラーは次のようになります。
public class AnimalController : ApiController
{
private AnimalRepository repository;
public AnimalController()
{
this.repository = new AnimalRepository();
}
public Dog[] Get()
{
return this.repository.GetAllAnimals();
}
public HttpResponseMessage Post(Dog animal)
{
this.repository.SaveAnimal(animal);
var response = Request.CreateResponse<Dog>(System.Net.HttpStatusCode.Created, animal);
return response;
}
私の Index.cshtml は次のようになります。
<header>
<div class="content-wrapper">
<div class="float-left">
<p class="site-title">
<a href="~/">Field<b>Connect</b></a></p>
</div>
</div>
</header>
<div id="body">
<ul id="animals"></ul>
<form id="saveForm" method="post">
<h3>New Dog</h3>
<p>
<label for="name">Name:</label>
<input type="text" name="name" />
</p>
<p>
<label for="breed">Breed:</label>
<input type="text" name="breed" />
</p>
<p>
<label for="size">Size:</label>
<input type="text" name="size" />
</p>
<p>
<label for="coatType">Coat Type:</label>
<select name="coatType">
<option value="Long">Long Hair</option>
<option value="Short">Short Hair</option>
<option value="Curly">Curly Hair</option>
</select>
</p>
<input type="button" id="saveAnimal" value="Save" />
</form>
</div>
@section scripts{
<script type="text/javascript">
$(function () {
$.getJSON('/api/animal', function (contactsJsonPayload) {
$(contactsJsonPayload).each(function (i, item) {
$('#animals').append('<li>' + item.name + '</li>');
});
});
});
$('#saveAnimal').click(function () {
$.post("api/animal",
$("#saveForm").serialize(),
function (value) {
$('#animals').append('<li>' + value.name + '</li>');
},
"json"
);
});
</script>
}
これはすべて正常に機能します。定義されたコレクションの一部である 2 匹の犬が Web ページに表示されます。ただし、私がやろうとしているのは、新しい犬をコレクションに保存する前に、その犬が現在コレクションに存在するかどうかを確認することです。そこで、AnimalRepository.cs の次のコード行の直後に forach ループを実装し始めました。コード行。
// Check to see if the name of the animal already exists
for (int i = 0; i < currentData.Count; i++)
{
foreach (var item in currentData[i])
{
if (item.Equals(currentData[i].name))
{
nameExists = true;
}
}
}
しかし、ビルドすると、IEnumerable を実装しない限り、このコレクションを反復処理できないというエラーが表示されるので、そうしました。追加しました: IEnumerable をクラスに追加して、インターフェイスから継承し、Dog クラスに次のコードを追加しました。
public class Dog : IEnumerable<Dog>
{
public string name { get; set; }
public string breed { get; set; }
public string size { get; set; }
public CoatType coatType { get; set; }
private List<Dog> dogs;
public IEnumerator<Dog> GetEnumerator()
{
if (dogs != null)
{
foreach (Dog dog in dogs)
{
if (dog == null)
{
break;
}
yield return dog;
}
}
}
IEnumerator IEnumerable.GetEnumerator()
{
// Lets call the generic version here
return this.GetEnumerator();
}
}
public enum CoatType
{
Long,
Short,
Curly
};
しかし、コードを実行すると、ページの上部に犬の名前が表示される代わりに、「未定義」と表示されます。Dog の代わりに文字列型の IEnumerable を返そうとしましたが、これは役に立ちませんでした。これを解決する方法はありますか?