MVC 2 Conversion Disrupts the parameters passed to my Stored Procedure
I have a few textboxes that are not required. If the user enters nothing it is passed as 'null' in MVC 2. It was passed as '""' in MVC 1. What changes can I make to accomodate for this?
public string Name { get; set; }
public string Offer{ get; set; }
public string AutoID { get; set; }
using (SqlConnection connect = new SqlConnection(connections))
{
SqlCommand command = new SqlCommand("Info_Add", connect);
command.Parameters.Add("autoID", SqlDbType.BigInt).Direction = ParameterDirection.Output;
command.Parameters.Add(new SqlParameter("name", Name));
//Offer now returns a null value, which cannot be passed
command.Parameters.Add(new SqlParameter("offer", Offer));
command.CommandType = CommandType.StoredProcedure;
connect.Open();
command.ExecuteNonQuery();
AutoID = command.Parameters["autoID"].Value.ToString开发者_StackOverflow();
}
Change your model binder:
public class EmptyStringModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
bindingContext.ModelMetadata.ConvertEmptyStringToNull = false;
return base.BindModel(controllerContext, bindingContext);
}
}
and then in global.asax:
ModelBinders.Binders.DefaultBinder = new EmptyStringModelBaseBinder();
This will revert to default settings from MVC 1. bindingContext.ModelMetadata.ConvertEmptyStringToNull
property is responsible for conversion to null
.
Check the properties with string.IsNullOrEmpty()
and if its true then set some default value to it.
This way it works both for ASP.NET MVC 1 and ASP.NET MVC 2
Another way to override the ModelBinder behaviour is to override the GetPropertyValue, this is where the ConvertEmptyStringToNull magic happens:
namespace System.Web.Mvc
{
class KeepEmptyStringsEmptyModelBinder : DefaultModelBinder
{
protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
{
return propertyBinder.BindModel(controllerContext, bindingContext);
}
}
}
Brian
精彩评论