gpt4 book ai didi

asp.net - MVC 3 空查询字符串参数值绑定(bind)为空字符串而不是 null

转载 作者:行者123 更新时间:2023-12-02 19:02:30 32 4
gpt4 key购买 nike

我有以下内容:

此操作:

public virtual ActionResult Search(string search, string sort)
{
...
}

使用空查询字符串参数从此 URL 调用:

http://myurl.com/mycontroller/search?search=&sort=

现在我的理解是,从 MVC 2 开始,DefaultModelBinder 会将这些值保留为空。然而,我发现它们实际上被设置为空字符串。这实际上是预期的行为吗?这是否记录在任何地方?

谢谢

最佳答案

是的,默认行为是将空字符串设置为 null,但可以通过更改 ConvertEmptyStringToNull = false; 来覆盖它。

true if empty strings that are posted back in forms should be converted to null;
otherwise, false. The default value is true.

msdn

就像这段代码:

public class SimpleArrayModelBinder : DefaultModelBinder 
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType == typeof(string))
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
bindingContext.ModelMetadata.ConvertEmptyStringToNull = false;
if (value == null || value.AttemptedValue.IsNullOrEmpty())
return "";
else
return value.AttemptedValue;
}
}
}

更改默认行为的另一种方法是使用模型中属性上方的 ConvertEmptyStringToNull 属性。

示例:

public class Person
{
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Lastname { get; set; }
...
}

Blog

关于asp.net - MVC 3 空查询字符串参数值绑定(bind)为空字符串而不是 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11023124/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com