この単純なコントローラーについて考えてみます。
Porduct product = new Product(){
// Creating a product object;
};
try
{
productManager.SaveProduct(product);
return RedirectToAction("List");
}
catch (Exception ex)
{
ViewBag.ErrorMessage = ex.Message;
return View("Create", product);
}
さて、私のCreate
見解では、ViewBag
オブジェクトをチェックして、Error
プロパティがあるかどうかを確認したいと思います。エラープロパティがある場合は、ユーザーにエラーメッセージを表示するために、ページにJavaScriptを挿入する必要があります。
これを確認するための拡張メソッドを作成しました。
public static bool Has (this object obj, string propertyName)
{
Type type = obj.GetType();
return type.GetProperty(propertyName) != null;
}
次に、Create
ビューで、次のコード行を記述しました。
@if (ViewBag.Has("Error"))
{
// Injecting JavaScript here
}
ただし、次のエラーが発生します。
null参照でランタイムバインディングを実行できません
何か案が?