MVC : using Json pass enum value

4/1/2014·1 min read

What's if i pass value from client to server as Json post, and server side's paramter would be enum. This's article is about that. Basically, you should use Nullable, otherwise, it'll throw exception by .NET.

1. Your enum

2. Controller(failed case)

If you define a parameter like this, it'll throw exception when you call it.

3. Sample HTML


4. Sample Javascript


5. result

When you click button without enter anything, which is empty, it'll throw exception.

6. Resolve

Basically, add ? to your enum. Then, if you passing is not enum int value, it'll pass as null to server side.

7. Compare result

So, basically, you could use ? if you passing enum to your controller. Since .net convert client value to enum works fine so far, it's better to use Nnum?, then you don't need to convert from string or int to your enum again at your C# code.