Friday, March 25, 2011

Removing validation errros of unused fields ASP.NET MVC

We are using ORM tools to create our Model objects and we may not be using all the properties in the page, So validation is going to be thrown irrespective of the properties used in the page.

In these scenarios we can use ActionFilterAttribute. We should override the OnActionExecuting method to remove the validations for un used properties.

public class UsedFieldsOnlyValidationAttribute : ActionFilterAttribute{

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var modelState = filterContext.Controller.ViewData.ModelState;
var valueProvider = filterContext.Controller.ValueProvider;

var keysWithNoIncomingValue = modelState.Keys.Where(x => !valueProvider.ContainsPrefix(x));
foreach (var key in keysWithNoIncomingValue)
{
modelState[key].Errors.Clear();
}
}
}

Submit Link Button for ASP.NET MVC

We are using submit buttons (input type=submit) for submitting the form back to the server.

We have other buttons in the page as link button, so we had different look & feel between submit button and others.

We wanted create a submit button that looks like other link button as well as it should do the submit functionality by own.

So we decided to create a extension method.

To submit the page, i used the below code in the href.
document.forms['" + formId + "'].action = '" + href + "';
document.forms['" + formId + "'].method = 'POST';document.forms['" + formId + "'].submit();


To manually call the microsoft client side validation, i used the below code in the href.
Sys.Mvc.FormContext.getValidationForForm(document.forms['" + formId + "']).validate('submit').length

Find the extension method below

public static MvcHtmlString SubmitLinkButton(this HtmlHelper helper,
string caption,
string actionName,
string id,
string formId,
RouteValueDictionary routeValues = null,
Dictionary htmlAttributes = null)
{
return CreateLinkButton(helper, caption, actionName, id, routeValues, htmlAttributes, formId, null);
}

private static MvcHtmlString CreateLinkButton(HtmlHelper helper,
string caption,
string actionName,
string id,
RouteValueDictionary routeValues = null,
Dictionary htmlAttributes = null,
string formId = null,
string href = null)
{
string cssClass = "t-grid-action t-button t-state-default";

if (href != null)
{
href = "#";
}
else
{
formId = formId ?? "0";
//creating href string
href += "/" + helper.ViewContext.RouteData.Values["controller"].ToString();
href += "/" + actionName;
//QueryString can be found here - helper.ViewContext.Controller.ControllerContext.HttpContext.Request.QueryString
if (routeValues != null && routeValues.Count > 0)
{
href += "?";
href = routeValues.Aggregate(href, (current, routeValue) => current + (routeValue.Key + "=" + routeValue.Value + "&"));
href = href.Substring(0, href.Length - 1);
}
href = "javascript:{if (!Sys.Mvc.FormContext.getValidationForForm(document.forms['" + formId + "']).validate('submit').length) { document.forms['" + formId + "'].action = '" + href + "';document.forms['" + formId + "'].method = 'POST';document.forms['" + formId + "'].submit();}}";
}

var linkButtonBuilder = new TagBuilder("a");
linkButtonBuilder.GenerateId(id);
linkButtonBuilder.MergeAttributes(htmlAttributes);
linkButtonBuilder.AddCssClass(cssClass);
linkButtonBuilder.MergeAttribute("print_mode", "hide");
linkButtonBuilder.MergeAttribute("href", href);
linkButtonBuilder.SetInnerText(caption);

return MvcHtmlString.Create(linkButtonBuilder.ToString());
}

Monday, January 31, 2011

Restarting Windows7 machines

We can use the following shutdown command to restart or logoff windows 7 machines from local or remote.

Shutdown /? - help
Shutdown /i - ui, where we can set action, reason, machine name(s)
Shutdown -r - restart

This is excellent one when working in the machine remotely and need a restart. This is very helpful for the admins too.

Monday, January 3, 2011

TryUpdateModel vs Model.IsValid

I am intensively working in asp.net mvc since last September and below is my findings about TryUpdateModel and Model.IsValid.

TryUpdateModel
This method can be used to bind the view to model when we didn't pass the model as parameter to action method. This has multiple overloads that will help to set only specific object if multiple subobjects found in the model, exclude some properties and so on. For your info, this method's last line returns the Model.IsValid.

Public ActionResult Update(string id)
{
//getting the object from the db
object obj = GetObjectById(id);
//binding the view to the model and validating the model
If(TryUpdateModel(obj))
{
UpdateObject(obj);
RedirectToAction("Index");
}
return View(obj);
}

Model.IsValid

This can be used to validate the model when we pass the model as a parameter. When we pass the model as a parameter the model binding is happening automatically and validation status is set to IsValid.

Public ActionResult Update(object obj)
{
//binding the view to the model and validating the model
If(Model.IsValid)
{
UpdateObject(obj);
RedirectToAction("Index");
}
return View(obj);
}