Question

I have a strong need to use custom input naming rules like:

<input type="text" value="1" name="products[123][qty]">

Can't use @HtmlTextBoxFor()

I decided to move "products" and "qty" text literals to be constants. Have a strong need for it too.

Then I tried:

<input id="qty" type="text" value="1" name="@OrderContext.PRODUCTS_KEY[123][@OrderContext.QUANTITY_KEY]">

And I get an error because "[" and "]" are used in Razor like index separators, I need to use it like string literals. I tried to escape them with "\" but then I get "\[" and "\]" in HTML instead of desired "[" and "]".

How to escape square brackets properly? What can you suggest?

The real need is to move input name keys like "products" and "qty" to be defined and later changed in one place.

Was it helpful?

Solution

Try

<input id="qty" type="text" value="1" name="@(OrderContext.PRODUCTS_KEY)[123][@OrderContext.QUANTITY_KEY]">

Parentheses right after @ limits the scope of the parsing as code to just the content within the parentheses.

OTHER TIPS

You could argue that what your doing is data related. So it belongs in the model. So edit your model thus:

public class OrderContext
{
  public string PRODUCTS_KEY {get; set;}
  public int QUANTITY_KEY {get; set;}
  public string PRODUCTS_KEY_InputName
  {
    get
    {
      return string.format("{0}[123][{1}]", PRODUCTS_KEY, QUANTITY_KEY);

    }
  }

}

View

then you can simply print it in your view:

<input id="qty" type="text" value="1" name="@PRODUCTS_KEY_InputName">
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top