MVC : using Json pass View Model


This article will show you how to passing View Model to your controller and get result to display to client side. In the example, View Model have type as int, string, bool, enum, DateTime, decimal. So we could see how these values are passing from client to server side.

1. View Model classes.

Put some regular type, int, string, bool and etc. So basically, all of them are using Nullable type, the reason, is when passing some value is not the type you specify or empty value from client side. Before come to controller, .NET'll throw exception error. Use Nullable good thing is you don't need to convert value again, like you don't need to convert string to int. Since .NET already did convert json value to the type you want. But if your business rule need to pass very complex case of value from client, and don't want it to be null, when it's not the type you specify, you could use string, and convert again under your controller. (* Json string has Max length, if your string is over then that, it could throw exception before come to your controller)

2. UI(from browser)


3. How HTML looks like


4. How Javascript looks like


5. Controller


6. result after click button


Since, MVC doesn't has ASP.NET's auto post, which dosen't automatic add any javascript to enable post to the server side. So, when you want to talk to server and it's not post, it's better way to use Json, since it's not refresh the web page.