ASP.Net MVC:在单个参数中提交数组/集合

发布于 2024-10-17 05:39:41 字数 350 浏览 3 评论 0原文

是否可以(以及如何)发送带有存储在单个参数中的数组的 post 请求?喜欢

myStringArray=你好,世界

以及接受此参数作为数组的操作,以 , 作为分隔符,

public ActionResult MyAction(string[] myStringArray)
{
  //myStringArray[0] == "hello" and myStringArray[1] == "world"
}

参数 myStringArray 的格式并不重要。但它必须是单个参数。

谢谢

Is it possible (and how) to send a post request with an array stored in a single parameter? like

myStringArray=hello,world

and an action that accepts this parameter as an array with , as separator

public ActionResult MyAction(string[] myStringArray)
{
  //myStringArray[0] == "hello" and myStringArray[1] == "world"
}

the format of the parameter myStringArray doesn't matter. But it has to be a single parameter.

Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

她说她爱他 2024-10-24 05:39:42

取决于您如何将数据发送到服务器。如果您从 url 参数或普通文本框执行此操作,其中包含以下数据:

<input id="myString" name="myString" type="text" value="hello,world" />

那么您不需要数组参数,只需用逗号将字符串拆分为数组即可:

public ActionResult MyAction(string myString)
{
    string[] myStringArray = myString.Split(',');
}

但如果您通过 AJAX 发送此内容,您也可以直接发送它。如果你想发送一个真实的数组,那么你的javascript应该如下所示 答案

Depends on how you are sending the data to the server. If you are doing this from a url param or normal textbox which has data like:

<input id="myString" name="myString" type="text" value="hello,world" />

Then you dont need an array parameter, just split the string by commas into an array:

public ActionResult MyAction(string myString)
{
    string[] myStringArray = myString.Split(',');
}

But if you are sending this by AJAX, you also send it directly. If you want to send a real array, then your javascript should look like this answer.

摇划花蜜的午后 2024-10-24 05:39:42

这是我在这个场景中使用的 IModelBinder。

    public class DelimitedArrayModelBinder : IModelBinder
    {
        public DelimitedArrayModelBinder()
            : this(null)
        {
        }

        public DelimitedArrayModelBinder(params string[] delimiters)
        {
            m_delimiters = delimiters != null && delimiters.Any()
                ? delimiters
                : new[] { "," };
        }

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            // type must be an array
            if (!bindingContext.ModelType.IsArray)
                return null;

            // array must have a type
            Type elementType = bindingContext.ModelType.GetElementType();
            if (elementType == null)
                return null;

            // value must exist
            ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            if (valueProviderResult == null)
                return null;

            string strValue = valueProviderResult.AttemptedValue;
            if (string.IsNullOrEmpty(strValue))
                return null;

            List<object> items = new List<object>();
            foreach (string strItem in strValue.Split(m_delimiters, StringSplitOptions.RemoveEmptyEntries))
            {
                try
                {
                    object item = Convert.ChangeType(strItem, elementType);
                    items.Add(item);
                }
                catch (Exception)
                {
                  // if we can't convert then ignore or log
                }
            }

            // convert the list of items to the proper array type.
            Array result = Array.CreateInstance(elementType, items.Count);
            for (int i = 0; i < items.Count; i++)
                result.SetValue(items[i], i);

            return result;
        }

        private readonly string[] m_delimiters;
    }

Here is an IModelBinder that I've been using for this scenario.

    public class DelimitedArrayModelBinder : IModelBinder
    {
        public DelimitedArrayModelBinder()
            : this(null)
        {
        }

        public DelimitedArrayModelBinder(params string[] delimiters)
        {
            m_delimiters = delimiters != null && delimiters.Any()
                ? delimiters
                : new[] { "," };
        }

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            // type must be an array
            if (!bindingContext.ModelType.IsArray)
                return null;

            // array must have a type
            Type elementType = bindingContext.ModelType.GetElementType();
            if (elementType == null)
                return null;

            // value must exist
            ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            if (valueProviderResult == null)
                return null;

            string strValue = valueProviderResult.AttemptedValue;
            if (string.IsNullOrEmpty(strValue))
                return null;

            List<object> items = new List<object>();
            foreach (string strItem in strValue.Split(m_delimiters, StringSplitOptions.RemoveEmptyEntries))
            {
                try
                {
                    object item = Convert.ChangeType(strItem, elementType);
                    items.Add(item);
                }
                catch (Exception)
                {
                  // if we can't convert then ignore or log
                }
            }

            // convert the list of items to the proper array type.
            Array result = Array.CreateInstance(elementType, items.Count);
            for (int i = 0; i < items.Count; i++)
                result.SetValue(items[i], i);

            return result;
        }

        private readonly string[] m_delimiters;
    }
听闻余生 2024-10-24 05:39:42

如果您创建一个包含数组的模型,那么应该没有问题。当然,您需要一个能够利用该强类型的视图(单击“创建强类型视图”并在列表中找到您刚刚创建的视图模型),您应该没有问题。

If you create a model with an array in it you should have no trouble. Then of course you nee a view that will utilize that strong type (click "Create a strongly-typed view" and find your view-model you just created in the list) you should have no problem.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文