MVC 2转换中断传递给我的存储过程的参数

MrM*_*MrM 0 c# asp.net-mvc asp.net-mvc-2

我有一些不需要的文本框.如果用户输入任何内容,则在MVC 2中将其作为"null"传递.它在MVC 1中作为"""传递.我可以进行哪些更改以适应此目的?

    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();
        }
Run Code Online (Sandbox Code Playgroud)

Luk*_*Led 12

更改模型绑定器:

public class EmptyStringModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        bindingContext.ModelMetadata.ConvertEmptyStringToNull = false;
        return base.BindModel(controllerContext, bindingContext);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在global.asax中:

ModelBinders.Binders.DefaultBinder = new EmptyStringModelBaseBinder();
Run Code Online (Sandbox Code Playgroud)

这将从MVC 1恢复为默认设置.bindingContext.ModelMetadata.ConvertEmptyStringToNull属性负责转换为null.