【问题标题】:MVC: String to Long ArrayMVC:字符串到长数组
【发布时间】:2015-09-02 15:58:39
【问题描述】:

我有一个名为“LongArray”的输入字段,我想在其中放置一个数字列表(例如“100、101、102”)。

如何将这些数字存储在输入字段中,以便在发布此表单时模型绑定器自动将“LongArray”值转换为 Post-Controller-Action 中预期模型的 long[] LongArray

【问题讨论】:

  • 你的意思是long[] longList = stringlist.Split(',').Select(x => long.Parse(x.Trim())).ToArray();

标签: c# asp.net asp.net-mvc forms razor


【解决方案1】:

最简单的方法是使用 FormCollection 并手动将字符串解析为数组。

[HttpPost]
public ActionResult MyActionMethod(FormCollection form)
{
    if (ModelState.IsValid)
    {
        const string name = "LongArray";

        IList<long> longArray = form[name] != null
            ? form[name].Split(new[] { ',' }, 
                StringSplitOptions.RemoveEmptyEntries).Select(x => Convert.ToInt64(x)).ToList()
            : new List<long>();


        // Some other fields
        string someInputValue = form["SomeInput"];
    }
    ...
}

【讨论】:

    【解决方案2】:

    您可以使用名为“LongArray”的 javascript 为每个输入动态添加输入。

    然后,如果您的操作与此类似,模型绑定器将拾取它。

    public ActionResult Post(long[] LongArray)
    {
       ...
    }
    

    这是一个简单的例子:

    HTML

    <div id="aDiv"></div>
    <input id="numberInput" type="text" >
    <button id="add">Add</button>
    

    JavaScript

    $('#add').click(function () {         
        var anInput = '<input type="hidden" name="LongArray" value=' + $('#numberInput').val() + '></input>';        
        $(anInput).appendTo('#aDiv');
        $('#numberInput').val('');
    });
    

    jsFiddle

    上面的简单附加了一个隐藏的输入,其中包含模型绑定器工作所需的名称。

    单个条目是通过输入时清除的文本框添加的。

    这会在浏览器中隐藏的 html 中呈现以下内容:

    【讨论】:

    • 但是只有一个输入字段的值没有办法做到这一点?
    • @Palmi 您可以有一个输入字段,用于添加您清除的值并将输入隐藏。将添加一个简单的示例。 2 分钟。
    • 谢谢。但是肯定没有更优雅的解决方案只有一个输入字段吗?例如 。有没有办法查看模型绑定器对这个输入做了什么?
    【解决方案3】:

    为此,您需要一个自定义模型绑定器:

    public class LongBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (controllerContext.HttpContext.Request.Form[bindingContext.ModelName] != null)
            {
                var decodedString = WebUtility.HtmlDecode(controllerContext.HttpContext.Request.Form[bindingContext.ModelName]);
                return decodedString.Split(',').Select(s => long.Parse(s.Trim())).ToArray();
            }
            return base.BindModel(controllerContext, bindingContext);
        }
    }
    

    现在如果你有这样的看法:

    @using (Html.BeginForm())
    {
        <input name="longArray" value="123, 345, 678" />
        <input type="submit" value="submit" />
    }
    

    你有这样的动作方法:

    [HttpPost]
    public ActionResult TestLong([ModelBinder(typeof(LongBinder))]long[] longArray)
    {
        // now your longArray contains your desired value.
    
    }
    

    【讨论】:

      猜你喜欢
      • 2014-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-15
      • 2014-10-24
      • 2018-09-20
      相关资源
      最近更新 更多