如何使用 asp-route 传递数组?

huangapple go评论86阅读模式
英文:

How to pass array using asp-route?

问题

Form 返回的 URL 格式:localhost2343/index?Colors=red&Colors=blue&Colors=pink

asp-route 返回的 URL 格式:localhost2343/index?Colors=red,blue,pink

如果我使用 form 提交按钮,一切都看起来很好。但是如果我点击 sort 超链接,它会传递 URL Colors=System.String%5B%5D

我如何将 Colors 的值传递到 asp-route 中?

<form asp-page="./index" method="get">
    <select asp-for="Colors" asp-items="@Model.Colors_SELECT" class="MultiSelect" multiple>
        <option value="">All</option>
    </select>
    <!-- ... -->
</form>

<Table>
    <!-- ... -->
    <a asp-page="./Index" method="get" 
       asp-route-SortOrder="@Model.Colors_Sort" 
       asp-route-SearchString="@Model.SearchString"
       asp-route-Colors="@Model.Colors">
        @Html.DisplayNameFor(model => model.MyList[0].Colors)
    </a>
    <!-- ... -->
</table>
[BindProperty(SupportsGet = true)]
public string[]? Colors { get; set; }
public SelectList? Colors_SELECT { get; set; }

public async Task OnGetAsync()
{
    // Form - URL 格式
    // 从 URL 获取值并设置到 SelectList 中
    var result = Request.Query["Colors"];
    var i = 0;
    foreach (string? item in result)
    {
        Colors[i] = item;
        i++;
    }
}

更新 - 我尝试了这个,但在 sort 链接上,它删除了 Sort 变量,并且只选择了一个 Colors(而不是多个):

<a asp-page="./Index" method="get" 
   asp-route-SortOrder="@Model.Colors_Sort" 
   asp-all-route-data="@Model.routeData">
    <!-- ... -->
</a>
[BindProperty(SupportsGet = true)]
public Dictionary<string, string> routeData { get; set; }

// ...

var routeData = new Dictionary<string, string>();
routeData.Add("SortOrder", CurrentSort);
routeData.Add("SearchString", SearchString);
for (int i = 0; i < result.Count; i++)
{
    var myParam = result[i];
    routeData.Add($"Colors{i}", myParam.ToString());
}

希望这可以帮助你解决问题。

英文:

Form returns url format: localhost2343/index?Colors=red&amp;Colors=blue&amp;Colors=pink

asp-route return url format: localhost2343/index?Colors=red,blue,pink

If I use form submit button than everything seems good. But If i click on sort hyperlink than it will pass URL Colors=System.String%5B%5D

How can I pass value of Colors inside asp-route?

&lt;form asp-page=&quot;./index&quot; method=&quot;get&quot;&gt;
     &lt;select asp-for=&quot;Colors&quot; asp-items=&quot;@Model.Colors_SELECT&quot; class=&quot;MultiSelect&quot; multiple&gt;
        &lt;option value=&quot;&quot;&gt;All&lt;/option&gt;
   &lt;/select&gt;
    ...
&lt;/form&gt;


&lt;Table&gt;
  ...
    &lt;a  asp-page=&quot;./Index&quot; method=&quot;get&quot; 
        asp-route-SortOrder=&quot;@Model.Colors_Sort&quot; 
        asp-route-SearchString=&quot;@Model.SearchString&quot;
        asp-route-Colors=&quot;@Model.Colors&quot;&gt;
           @Html.DisplayNameFor(model =&gt; 
    model.MyList[0].Colors)
     &lt;/a&gt;
...
&lt;/table&gt;


  [BindProperty(SupportsGet = true)]
    public string[]? Colors { get; set; }
    public SelectList? Colors_SELECT { get; set; }

public async Task OnGetAsync()
{
   // Form - URL Format 
   // get values from URL &amp; set inside selectlist 
   var result = Request.Query[&quot;Colors&quot;];
   var i = 0;
   foreach (string? item in result) {
          Colors[i] = item;
          i++;
   }
}

Update - I tried this but on sort link, it removes Sort variable & it picks only 1 Colors (not multi)

    &lt;a  asp-page=&quot;./Index&quot; method=&quot;get&quot; 
        asp-route-SortOrder=&quot;@Model.Colors_Sort&quot; 
        asp-all-route-data=&quot;@Model.routeData&quot;&gt;
          
           [BindProperty(SupportsGet = true)]
           public Dictionary&lt;string, string&gt; routeData { get; set; }
             ....
           var routeData = new Dictionary&lt;string, string&gt;();
            routeData.Add(&quot;SortOrder&quot;, CurrentSort);
            routeData.Add(&quot;SearchString&quot;, SearchString);
            for (int i = 0; i &lt; result.Count; i++)
            {
              var myParam = result[i];
             routeData.Add($&quot;Colors{i}&quot;, myParam.ToString());
            }

答案1

得分: 1

这可能有所帮助:
要从Razor页面中的选择元素中获取所选值,您可以使用 Request.Form["selectName"] 集合。
例如,考虑以下 select 元素:

@page "{Colors}"

<form method="post">
  <select multiple name="colors">
    <option value="red">Red</option>
    <option value="blue">Blue</option>
    <option value="pink">Pink</option>
  </select>
  <button type="submit" asp-page-handler="GetColors">Submit</button>
</form>

要在表单提交处理程序中获取所选值并修改URL中的查询字符串以包含所选值(red, blue, pink),您可以尝试以下代码:

public IActionResult OnGet(string? Colors)
{
    if (string.IsNullOrWhiteSpace(Colors))
    {
        // 做某事
        return Page();
    }

    if (!string.IsNullOrWhiteSpace(Colors))
    {
        // 做某事
        return Page();
    }

    return Page();
}

public IActionResult OnPostGetColors()
{
    IDictionary<string, string> parameters = new Dictionary<string, string>();
    var selectedColors = string.Join(",", Request.Form["colors"]);
    parameters.Add("Colors", selectedColors);
    string query = "";
    foreach (var param in parameters)
        query += $"{param.Key}={param.Value}";

    var url = $"{HttpContext.Request.Path}?{query}";
    return Redirect(url); // url : https://localhost:7272/index?Colors=red,blue,pink
}

此代码将帮助您通过URL作为查询字符串提交所选值,然后将用户重定向到包含所选值的新URL,这些值作为颜色参数的多个值添加到查询字符串中。

英文:

This may help:
To get the selected values from a select element in a Razor page, you can use the Request.Form[&quot;selectName&quot;] collection.
For example, consider the following select element:

@page &quot;{Colors}&quot;


&lt;form method=&quot;post&quot;&gt;
  &lt;select multiple name=&quot;colors&quot;&gt;
    &lt;option value=&quot;red&quot;&gt;Red&lt;/option&gt;
    &lt;option value=&quot;blue&quot;&gt;Blue&lt;/option&gt;
    &lt;option value=&quot;pink&quot;&gt;Pink&lt;/option&gt;
  &lt;/select&gt;
  &lt;button type=&quot;submit&quot; asp-page-handler=&quot;GetColors&quot;&gt;Submit&lt;/button&gt;
&lt;/form&gt;

To get the selected values in the form submission handler and modify the query string in the URL and include the selected values (red, blue, pink), you can try the following code:

public IActionResult OnGet(string? Colors)
{
	if (string.IsNullOrWhiteSpace(Colors))
	{
		// do something
		return Page();
	}

	if (!string.IsNullOrWhiteSpace(Colors))
	{
		// Do something
		return Page();
	}

	return Page();
}


public IActionResult OnPostGetColors()
{
    IDictionary&lt;string, string&gt; params = new Dictionary&lt;string, string&gt;();
	var selectedColors = string.Join(&quot;,&quot;, Request.Form[&quot;colors&quot;]);
	params.Add(&quot;Colors&quot;, selectedColors);
	string query = &quot;&quot;;
	foreach (var p in params)
		query += $&quot;{p.Key}={p.Value}&quot;;

	var url = $&quot;{HttpContext.Request.Path}?{query}&quot;;
	return Redirect(url); // url : https://localhost:7272/index?Colors=red,blue,pink
}

This code will help you submit the selected values through the URL as a query string, and then will redirect the user to a new URL with the selected values added to the query string as multiple values for the colors parameter.

huangapple
  • 本文由 发表于 2023年1月9日 09:17:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75052422.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定