Wednesday, 16 July 2014

Validating your model before inserting into database in Asp.net MVC

We all are aware that when we take any model from view(user input) into the controller , we always tend to
use ModelState.IsValid to check if model is valid , then only we will proceed for further processing

[HttpPost]
[ValidateAntiForgeryToken]
public ViewResult Share( model_document param_model_document )
{
// VALIDATE THE MODEL
if(ModelState.IsValid) {
// DO THE DESIRED TASK
}
return View();
}
view raw gistfile1.cs hosted with ❤ by GitHub

But the same is not applicable when we are doing same in class file which does not inherit controller class.




For that we have to use GetValidationErrors() to validate if we are good with data models & should only proceed into database insertion once there are no errors ( GetValidationErrors().Count() ).


public Boolean MovedToFolder( int param_src_folderID , int param_des_folderID , int docmovID )
{
using(DBStore db = new DBStore()) {
//create some model class instance
//insert values
//db.somemodel.Add(modelobj);
return db.GetValidationErrors().Count() == 0 ? (db.SaveChanges() == 1 ? true : false) : false;
}
}
view raw gistfile1.cs hosted with ❤ by GitHub

Basics of Tree data structure

Tree data structure simulates a  hierarchical tree structure, with root and subtrees represented by linked nodes. Some Terminology Root...