2 回答

TA貢獻1871條經驗 獲得超8個贊
在 HTML 中沒有空值這樣的東西。輸入具有某個值或空值。甚至沒有辦法通過查看查詢參數來判斷值是字符串還是數字。
HTML 表單的默認行為是在提交時包含所有字段。因此,即使輸入沒有值,它仍將作為查詢的一部分包含在內。 并且都是表示沒有為字段輸入值的有效語法。www.example.com/xxx?str=
www.example.com/xxx
str
但是,您可以包括隱藏字段
<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 關注
- 206 瀏覽
添加回答
舉報