0

I am trying to get Razor (C#) and javascript to play nicely together but I can't seem to do it. I have searched the other articles on StackOverflow, but none of them seem to work for me.

Some noticeable differences from other posts and mine include the following:

I am using an external JavaScript file (not mandatory, but it is there).

I am using a cshtml file for the header layout for all pages (which puts the head tag in a different file than the one actually attempting to call the function.

I also use jQuery, if it would be easier that way.

What I am trying to accomplish:

All I need to do is get the contents of a tag (innerHTML, or .html in jQuery) (by id, class, whatever) and assign that value to "AppState["gEntryID"] for use with the next page.

Some things I have tried:

function entryClickHandler()
{
    @AppState["gEntryID"] = document.getElementById("tester").innerHTML;
}

AND

function entryClickHandler()
{
    <text>
    @AppState["gEntryID"] = document.getElementById("tester").innerHTML;
    </text>
}

I have tried these (and a few other variations on these) in both the external file and the head section within the HeaderLayout File.

I understand that C# runs before the page and the JavaScript mostly runs after the page (at least with events such as this).

Any help would be greatly appreciated.

2
  • Can I ask why you want to do this? Commented Sep 27, 2012 at 21:01
  • Because I am plotting entries dynamically based off of a dynamic sql query. Once done, they click on the entry they want and that entry is subsequently plotted on another "View & Edit" page, where they can look further into or update the entry. Since I never know how many entries I am dealing with I need to read the unique ID of the field they select. I suppose I could use a radio button and another input submit button and just post to the other page, but the current page already has one submit button. I've never used 2 submit buttons before, but I don't foresee a problem with it, I guess. Commented Sep 27, 2012 at 21:19

1 Answer 1

2

It doesn't work that way. You cannot set variables in the C#/Razor side with JavaScript without using a form post or ajax submit.

Javascript doesn't get access to the page until after Razor has done it's part and rendered and sent the page.

Sign up to request clarification or add additional context in comments.

2 Comments

That makes sense, do I need to use another library or plugin (like jQuery) to use AJAX? Or does it kind of work with jQuery? What AJAX call could I use?
Another problem is that this form already submits and uses if(IsPost), could I just redirect to new page with a different input submit button?

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.