开发者

get all form elements that end with "Max" as the id name

I basically have several input fields that share the same last 3 characters, "Max". They are all different from the "div" tags they are part of. The block of code I have right now looks terrible:

                    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)
                {
       开发者_JAVA百科             TempData["Max"] = Convert.ToInt32(Request.Form["PLDMax"]);
                }

How do i pass in any form elements that end with Max instead of having this redundant block of code?Thanks guys!!


Something like this:

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

[Edit]

I'm sorry didn't pay enough attention. I think this is what you need:

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


You could put all of the IDs into an array and then just loop through them:

(untested semi-pseudocode)

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;
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜