首页 > 解决方案 > ASP.NET Razor 页面中的可选查询字符串参数

问题描述

在我的高级搜索表单中,我有大约 25 个字段。当我提交表单时,所有参数都会传递给 URL,即使为 null。如何传递仅由用户更改并具有值的参数?所有 25 个字段都是可选的。

我有大约 25 个:

[BindProperty(SupportsGet = true)]
[Display(Name = "Foo")]
public int? Foo{ get; set; }

OnGetAsync:

public async Task<IActionResult> OnGetAsync()
{
   Properties = await _DarkMatterRepo.FindAsync(Foo, ...)
   return Page(); 
}

标签: asp.net-corerazor

解决方案


如何传递仅由用户更改并具有值的参数?

要实现上述要求,您可以尝试检查表单数据并导航到预期页面,如下所示。

形式代码

<form method="get">
    <input type="text" name="name">
    <input type="email" name="emailaddress">
    <input type="number" name="age">
    @*other input fields*@
    <input type="submit">
</form>

动态生成 QueryString 并导航到特定页面

<script>
    $( "form" ).on( "submit", function( event ) {
        event.preventDefault();
        //console.log($(this).serializeArray());
        var formdata = $(this).serializeArray();
        var parm = "";
        $.each(formdata, function (index, item) {
            if (item.value!="") {
                parm += item.name + "=" + item.value + "&";
            }
        });

        //console.log(parm.substring(0, parm.length - 1));

        window.location.href = "@Url.Page("Index")" + "?" + parm.substring(0, parm.length - 1);
    });
</script> 

推荐阅读