Logical comparison in MVC Controller using the string "false,true" after a form is submitted. Why? [closed]

StackOverflow https://stackoverflow.com/questions/21587736

  •  07-10-2022
  •  | 
  •  

Question

I'm modifying a C# MVC web application implemented by some other developer and sometimes I find the following logical comparison:

client.AttributeName = Request["AttributeName"] == "false,true";

Is this a correct expression? If so, what's this supposed to do?

Was it helpful?

Solution

In MVC you shouldn't really need to get values from the Request object - you should get them in the model or parameters passed into the action.

If you have two HTML inputs with the same name you get their values separated by commas in the result.

I'm guessing that you have an ASP.Net generated checkbox, as this actually outputs something like this:

<%:Html.Checkbox("AttributeName")%>

Becomes:

<input name="AttributeName" type="hidden" value="false" />
<input checked="checked" id="AttributeName" name="AttributeName" type="checkbox" value="true" />

The second input is there because if an HTML checkbox input is false it sends nothing back in the POST data. This HTML means that the returned value will be either:

  • "false,true" if the checkbox is checked
  • "false" if the checkbox is not checked

ASP.Net's handlers know how to cope with this, but your predecessor did not.

Here is another question on why .Net does this.

To fix it you can rely on MVC's built in handling:

public ActionResult YourAction(bool AttributeName) 
{
    client.AttributeName = AttributeName; 
}

MVC already knows to only accept the last POST back value in the comma separated list, so if you POST "false,true" to the method above AttributeName will be true.

OTHER TIPS

I have no idea if that's correct because you didn't say what it suppose to do.

But I can tell you what it does:

client.AttributeName = Request["AttributeName"] == "false,true";

From right to left: check if Request["AttributeName"] has the same value as "false,true" and assign the check result (true or false as bool value) to client.AttributeName.

It looks like it is setting client.AttributeName (Boolean) to true or false depending on whether the value in Request["AttributeName"] is equal to the string "false,true"

Not sure what it is supposed do do though - you haven't posted very much information.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top