Action Parameters Add a default value when No Key
How can I set up a default value in my Action Filter when an ActionParameter is empty?
When I use the About and Area_1419 Actions on my controller the filter works fine as it picks up the passed SectionID parameter. When I use the index action I get the error below….
The given key was not present in the dictionary. On this line...
var GetSectionID = filterContext.ActionParameters["SectionID"];
I don’t won’t to add the SectionID parameter to each controller action as it only applies to certain sections and I don’t want to add the filter to each action as the filter effects these pages aswell.
Is it possible to set up a default value for SectionID within the filter if no value is present for SectionID?
CategoriesAttribute
using System;
using System.Colle开发者_运维技巧ctions.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Website.ActionFilters
{
public class CategoriesAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var GetSectionID = filterContext.ActionParameters["SectionID"];
var NoSectionID = 1;
if (GetSectionID == null)
{
filterContext.Controller.ViewData["SectionID"] = NoSectionID;
}
else
{
filterContext.Controller.ViewData["SectionID"] = GetSectionID;
}
}
}
}
Home Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Website.Models;
using Website.ActionFilters;
namespace Website.Controllers
{
[HandleError,Categories]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About(int SectionID)
{
return View();
}
public ActionResult Area_1419(int SectionID)
{
return View();
}
}
}
ActionParameters is a dictionary; check for the key via ActionParameters.ContainsKey("SectionID") first. With a dictionary, checking for a key never returns null, but throws that exception because it always expects the key.
if (filterContext.ActionParameters.ContainsKey("SectionID"))
{
//Code to process as section ID
filterContext.Controller.ViewData["SectionID"] = filterContext.ActionParameters["SectionID"];
}
else
{
//Code to process as if no section ID
filterContext.Controller.ViewData["SectionID"] = 1;
}
精彩评论