【问题标题】:get all form elements that end with "Max" as the id name获取所有以“Max”作为id名称结尾的表单元素
【发布时间】:2011-05-29 04:01:45
【问题描述】:

我基本上有几个输入字段共享相同的最后 3 个字符,“Max”。它们都与它们所属的“div”标签不同。我现在的代码块看起来很糟糕:

                    if (Convert.ToInt32(Request.Form["MCQMax"]) > 0)
                {
                    TempData["Max"] = Convert.ToInt32(Request.Form["MCQMax"]);
                }
                else if (Convert.ToInt32(Request.Form["SAMax"]) > 0)
                {
                    TempData["Max"] = Convert.ToInt32(Request.Form["SAMax"]);
                }
                else if (Convert.ToInt32(Request.Form["PLMCQMax"]) > 0)
                {
                    TempData["Max"] = Convert.ToInt32(Request.Form["PLMCQMax"]);
                }
                else if (Convert.ToInt32(Request.Form["PLIFMax"]) > 0)
                {
                    TempData["Max"] = Convert.ToInt32(Request.Form["PLIFMax"]);
                }
                else if (Convert.ToInt32(Request.Form["PLDMax"]) > 0)
                {
                    TempData["Max"] = Convert.ToInt32(Request.Form["PLDMax"]);
                }

我如何传递以 Max 结尾的任何表单元素,而不是使用这个冗余代码块?谢谢大家!!

【问题讨论】:

    标签: javascript asp.net html asp.net-mvc-3


    【解决方案1】:

    类似这样的:

    var firstMaxFormKey = Request.Form.AllKeys
         .Where(arg => arg.EndsWith("Max"))
         .FirstOrDefault();
    TempData["Max"] = Convert.ToInt32(Request.Form[firstMaxFormKey]);
    

    [编辑]

    很抱歉没有引起足够的重视。我想这就是你需要的:

    var max = Request.Form.AllKeys
            .Where(arg => arg.EndsWith("Max"))
            .Select(arg => Convert.ToInt32(Request.Form[arg]))
            .Where(arg => arg > 0)
            .FirstOrDefault();
    

    【讨论】:

    • 试试这个,谢谢回复!
    • @ValithX - 我用更好的代码示例更新了我的答案。希望这是您真正需要的。
    【解决方案2】:

    您可以将所有 ID 放入一个数组中,然后循环遍历它们:

    (未经测试的半伪代码)

    IDs={"MCAMax",...}
    
    for(int i=0; i<IDs.length; i++){
       int theMax=Convert.ToInt32(Request.Form[IDs[i]]);
       if ( theMax > 0){
          TempData["Max"] = theMax;
          break;
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-25
      • 1970-01-01
      • 1970-01-01
      • 2011-08-23
      • 1970-01-01
      • 2013-03-07
      • 2014-01-27
      • 2014-04-09
      • 2019-07-10
      相关资源
      最近更新 更多