2 回答
TA贡献1871条经验 获得超8个赞
在 HTML 中没有空值这样的东西。输入具有某个值或空值。甚至没有办法通过查看查询参数来判断值是字符串还是数字。
HTML 表单的默认行为是在提交时包含所有字段。因此,即使输入没有值,它仍将作为查询的一部分包含在内。 并且都是表示没有为字段输入值的有效语法。www.example.com/xxx?str=www.example.com/xxxstr
但是,您可以包括隐藏字段
<input name="IsEmptyString" type="hidden"/>
,然后使用 JavaScript 根据用于确定它是空还是空的任何逻辑来设置值。
TA贡献1828条经验 获得超4个赞
我发现了这个很棒的解决方案,从 https://stackoverflow.com/a/35966463/505893 复制并进行了改进。它是 Web 应用的全局配置中的自定义项。
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//treat query string parameters of type string, that have an empty string value,
//(e.g. http://my/great/url?myparam=) as... empty strings!
//and not as null, which is the default behaviour
//see https://stackoverflow.com/q/54484640/505893
GlobalConfiguration.Configuration.BindParameter(typeof(string), new EmptyStringModelBinder());
//...
}
}
/// <summary>
/// Model binder that treats query string parameters that have an empty string value
/// (e.g. http://my/great/url?myparam=) as... empty strings!
/// And not as null, which is the default behaviour.
/// </summary>
public class EmptyStringModelBinder : System.Web.Http.ModelBinding.IModelBinder
{
public bool BindModel(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
{
var vpr = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (vpr != null)
{
//parameter has been passed
//preserve its value!
//(if empty string, leave it as it is, instead of setting null)
bindingContext.Model = vpr.AttemptedValue;
}
return true;
}
}
- 2 回答
- 0 关注
- 223 浏览
添加回答
举报
