How to change model values before validating in ASP.NET MVC?

Sometimes, it is necessary to make modifications to your mvc model before they are validated.  For example, if you define an integer data type  and allow users to enter commas in the integer, when the form is submitted, the validation will fail because by default, the MVC framework will not recognize numeric strings with commas as integers.

Let’s dumb it up.

Here is the model:


public class TaxReturnModel

{

[Required]

public string FirstName {get; set; }

[Required]

public string LastName {get; set; }

[Range(1, 1000000)]

public int AnnualIncome {get; set; }

}

And here is our controller class


public class TaxReturnController: Controller

{

[HttpPost]

public ActionResult TaxInfo(TaxReturnModel model)

{

if (model.IsValid)

{

// Do something aobut this model.

}

return View(model);

}

}

As I said above, if the user enters 55,000 in the annual income textbox in the web form, the validation will fail upon submission. Of course, you can define AnnualIncome as a string, but I don’t like that idea and will not be discussed.

So, how to let 55,000 pass validation?

The idea is to intercept the value, remove the commas before it is validated. We will need to create a custom model binder and override the GetPropertyValue method like below:


public class TaxReturnModelBinder : DefaultModelBinder

{

protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext     bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)

{
if (propertyDescriptor.ComponentType == typeof(TaxReturnModel))
{
if (propertyDescriptor.Name == "AnnualIncome")
{
var obj = bindingContext.ValueProvider.GetValue("AnnualIncome");
return Convert.ToInt32(obj.AttemptedValue.ToString().Replace(",", ""));
}
}
return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
}

}

Then you need to update your controller action method as follows to use the custom model binder.

[HttpPost]

public ActionResult TaxInfo([ModelBinder(typeof(TaxReturnModelBinder))]TaxReturnModel model)

{

if (model.IsValid)

{

// Do something aobut this model.

}

return View(model);

}

This approach is offer by dotnetstep.

Want to overload your methods in WCF? Watch out!

http://jeffbarnes.net/blog/post/2006/09/21/Overloading-Methods-in-WCF.aspx

HttpContext.Current.User.IsInRole(string role)

public bool IsInRole(string role) 
{
    if (_Identity == null)
        throw new ProviderException(SR.GetString(SR.Role_Principal_not_fully_constructed));

    if (!_Identity.IsAuthenticated || role == null)
        return false;
    role = role.Trim();
    if (!IsRoleListCached) {
        _Roles.Clear();

        // here the RoleProvider is used to get the roles for the user
        // and are cached in a collection on the RolePrincipal so that
        // they are only fetched once per request
        string[] roles = Roles.Providers[_ProviderName].GetRolesForUser(Identity.Name);
        foreach(string roleTemp in roles)
            if (_Roles[roleTemp] == null)
                _Roles.Add(roleTemp, String.Empty);

        _IsRoleListCached = true;
        _CachedListChanged = true;
    }
    return _Roles[role] != null;
}

How to configure NLog for asp.net website application

It seems that NLog.config won’t be picked up by an asp.net website application.  The logger calls get executed, but I could not find the log file I configured in NLog.config.

I see from here that the NLog configuration information needs to be put into web.config.  I followed that example and had the following in web.config:

<target xsi:type=”File” fileName=”log.txt” name=”logfile” layout=”${date:format=yyyyMMddHHmmss} ${message}”/>

But, I still wasn’t able to find where the log.txt file is if at all it was created.  I then searched around and modified the above line to the following:

<target xsi:type=”File” fileName=”${basedir}/log.txt” name=”logfile” layout=”${date:format=yyyyMMddHHmmss} ${message}”/>

And then it worked.