如何在 url.action 中将列表作为参数传递?

编程


任何人都可以帮助我如何使用 url.action 将整数值列表从视图传递到 MVC 控制器?

解决方案2

C#
public ActionResult Index(string[] data)
{
    return View();
}

XML
@{
    var qs = HttpUtility.ParseQueryString("");
    new List<string>{"one", "two", "three"}.ForEach(s => qs.Add("data", s));
}
<a href="@Url.Action("Index", "Home")?@qs">click</a>

更新:

XML
@{
    ViewBag.name = "xyz";
    ViewBag.data = new List<string>{"one", "two", "three"};

    var q = HttpUtility.ParseQueryString("");
    q.Add("name", ViewBag.name);

    foreach (var item in ViewBag.data)
    {
        q.Add("data", item.ToString());
    }

}
<a href="@Url.Action("Index", "Home")?@q">click</a>

解决方案1

解决方案3

您可以使用

@Url.Action("Index", "home", new { data1 = 0, data2 = 0 })
SQL
public ActionResult Index(int data1, int data2)
{
    return View();
}

或者

@Url.Action("Index", "home", new { data = yourintlist })
SQL
public ActionResult Index(int[] data)
{
    return View();
}

解决方案4

你需要使用 & 对于列表中的每一项。
就像是,
ids=1&ids=2&ids=3

C#
string param = string.empty;
foreach(var item in list)
{
    param += "ids=" + item + "&";
}
param = param.Remove(param.Length - 1); // remove the last appended &
@Url.Action("Action", "Controller", new { data = param });

-KR

解决方案5

相反,类型转换为“object”或“object”[]”或使用 RouteValueDictionary。 实现相同目的的一个简单方法是使用“Newtonsoft.Json”

如果使用.Net Core 3.0或更高版本;

默认使用内置的 System.Text.Json 解析器实现。

JavaScript
@using System.Text.Json;

…….

@Url.Action("ActionName", "ControllerName", new {object = JsonConvert.SerializeObject(‘@ModalObject’)  }))

如果卡在使用 .Net Core 2.2 或更早版本;

默认使用 Newtonsoft JSON.Net 作为您的首选 JSON 解析器。

JavaScript
@using Newtonsoft.Json;

…..

@Url.Action("ActionName", "ControllerName", new {object = JsonConvert.SerializeObject(‘@ModalObject’)  }))

您可能需要先安装该软件包。

PM> Install-Package Newtonsoft.Json

然后,

C#
public ActionResult ActionName(string modalObjectJSON)
{
	Modal modalObj = new Modal();

	modalObj = JsonConvert.DeserializeObject<Modal>(modalObjectJSON);
	
}

コメント

タイトルとURLをコピーしました