Gotham Must Fall
Gotham Must Fall

Reputation: 111

How do I validate for a empty query string parameter in asp.net mvc3

I want to validate for a empty Id value in the url.

../Task/EditEmployee/afccb22a-7cfd-4be5-8f82-9bd353c13b16

I want that if the Id is empty

../Task/EditEmployee/

Than redirect the user to a certain page.

public ActionResult EditEmployee(Guid Id)

{

//Some code in here

}

Upvotes: 2

Views: 346

Answers (2)

Ufuk Hacıoğulları
Ufuk Hacıoğulları

Reputation: 38518

It may not be the best solution but you can take id parameter as string and try to parse it like this:

public ActionResult EditEmployee(string id)
{
    if(string.IsNullOrWhiteSpace(id))
    {
        // handle empty querystring
    }
    else
    {
        Guid guid;
        if (Guid.TryParse(id, out guid))
        {
            //Some code in here
        }
    }
}

Or

You can also create a regex constraint on the route but that may be too complicated and hard to understand. Map this route before the default one.

routes.MapRoute(
    "TastEditEmployee",
    "Task/EditEmployee/{id}",
    new { controller = "Task", action = "EditEmployee" },
    new { id = @"^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$" } 
);

Then you can use id parameter as Nullable Guid.

public ActionResult EditEmployee(Guid? id)
{
    //do something
}

Upvotes: 2

moribvndvs
moribvndvs

Reputation: 42495

Since Guid is a struct, the value of Id will be Guid.Empty if it was omitted. You can check for that.

public ActionResult EditEmployee(Guid Id)
{
   if (Id == Guid.Empty) throw new ArgumentException("Id not specified.");
}

Upvotes: 0

Related Questions