1

Trying to render the page, and trigger a notification on button click. I have set this up to just do a pop up for now, since its an internal application for the higher ups.

The button in question is a simple razor syntax html helper with an onclick event to return a confirm dialog. However it seems I am unable to render the item variable for this.

@Html.ActionLink("Delete", "Delete", new { id = item.Id },
 new { @class = "btn btn-warning", 
 onclick = "return confirm('WARNING: Delete @item.Id?');" })

this fails to render item.Id (the output of the surrounding foreach statement but instead outputs the string literal "@item.Id"

@Html.ActionLink("Delete", "Delete", new { id = item.Id }, 
 new { @class = "btn btn-warning", 
 onclick = "return confirm('WARNING: Delete ' + item.Id + '?');" })

This renders the variable but since it is not a javascript variable it renders as "Delete undefined ?"

How can I use a variable from the foreach outside of the javascript passed into this dialog, to make the message more descriptive.

2
  • 1
    Do string concatenation in onclick event Commented Jun 20, 2017 at 13:03
  • Bhuban thanks for the insight that is what I am trying to get to, however I cannot for the life of me remember/find the syntax can you elaborate with an example Commented Jun 20, 2017 at 13:07

2 Answers 2

2

I was able to solve my own problem using string.Format in C#.

@Html.ActionLink("Delete", "Delete", new { id = item.Id }, 
 new { @class = "btn btn-warning", 
 onclick = string.Format("return confirm('WARNING: Delete {0}?');", item.Id) })
Sign up to request clarification or add additional context in comments.

3 Comments

The reason you had to do it that way, is that you had already switched to "code" mode by starting a line with @. The razor compiler never even saw the @item.
Dave: makes perfect sense, Thank you for the details, hopefully this saves someone the far too long I spent on a stupid error
@Dave or as in my answer for their second example they were including a javascript variable instead of their foreach variable since the string wasn't concatenated correctly. Two ways to cut the cake.
0

You aren't closing your string properly. Try the following:

onclick = "return confirm('WARNING: Delete " + item.Id + "?');"

Your error is saying the javascript item item.Id is not defined because item is probably not defined in your js scripts.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.