views:

224

answers:

4

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();
        }
+1  A: 

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

Mahesh Velaga
MVC 1 was always ""
jfar
@jfar: sorry I didn't understand what u mean. what's wrong with the answer ?
Mahesh Velaga
A: 

Use the ?? operator. e.g. Name ?? ""

Hightechrider
+9  A: 

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.

LukLed
+1 I didn't know this can be done so easily at one place!
Mahesh Velaga
A: 

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

Brian Chance