2

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

}

2 Answers 2

2

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for the suggestion, I'm still very new in mvc and haven't done any mapping and therefor not familiar with it. I used your first suggestion and it worked perfectly, thank you!!
0

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.");
}

3 Comments

This will also throw an exception when id is not empty and not a value in Guid format.
Yes, and I don't think that's undesirable either.
Thank you very much but this returned an error message...I want it to validate the query string before it even reaches the code part where it requires the Id. I don't know if I am explaining it well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.