Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net Razor, Syntax error - onclick event parameter

Tags:

razor

<input type="button" value="Delete" onclick="deleteMember(@Model.ID, '@ViewBag.returnUrl')"/>

That code has 4 errors, 2 syntax error and 2 Unterminated string constant.

What should I do to fix these errors?

enter image description here

like image 241
Expert wanna be Avatar asked Mar 25 '13 14:03

Expert wanna be


2 Answers

You could break it out in a an Html.Raw Call:

<input type="button"
       value="Delete"
       onclick="@(Html.Raw(String.Format("deleteMember({0}, '{1}')",
           Model.ID,
           Html.Encode(ViewBag.returnUrl)
       )))"
/>

Or assign it to a string first, then reference that variable in the attribute.

@{
  String onclick = String.Format("deleteMember({0}, '{1}')",
      Model.ID, Html.Encode(ViewBag.returnUrl));
}
<input type="button" value="delete" onclick="@onclick" />

Third option is to separate concerns; Keep markup and scripts separate. Neil beat me to it, but something like:

<input type="button" value="delete"
    data-task="delete" data-id="@Model.ID" data-returnurl="@ViewBag.returnUrl" />

<!-- .... -->

<script>
  var buttons = document.getElementsByTagName('INPUT');
  for (var b = 0; b < buttons.length; b++){
    if (buttons[b].type != 'button') continue;
    switch (buttons[b].getAttribute('data-task') || ''){
      case 'delete':
        // read data-id & data-returnurl. Do something with them, and
        // move on.
        break;

      // other actions
      case 'add':
      case 'update':
      default:
        break;
    }
  }
</script>

Though it's strange the first parenthesis messes with razor (even though it's declared in an attribute). I wouldn't expect this behavior myself.

like image 65
Brad Christie Avatar answered Oct 05 '22 22:10

Brad Christie


It's more a bug in VS than anything else.

It think it would still render as you would expect.

I like Brad's solution.

Another recommended option is to pop your values into data-dash attributes and use something like jQuery to pass the data-dash values to your function.

like image 45
Neil Thompson Avatar answered Oct 05 '22 23:10

Neil Thompson