1

How do I call Jquery function from C#? I have tried using registerStartupScript but I don't understand how it works still and it isn't working anyway. It doesn't enter jquery function at all

Page page = new Page();
ScriptManager.RegisterStartupScript(page, this.GetType(), "script", "publishDialog();", true);
function publishDialog() {
    $(".alert").dialog({
        modal: true,
    });
}
<div class="alert">
    You must be signed in to upload music
</div>

Edit: If the user clicks on publish button and no files are selected then I want to display the jquery ui dialog popup box that tells them to select a file. I need this line uploadedSongs.Count(x => x.IsSelected) == 0 to check if they have not selected a file. Is their anyway I can get this into my jquery function then?

[HttpPost]
     public ActionResult Publish(IEnumerable<UploadedSong> uploadedSongs)
        {
            Page page = new Page();
            if (uploadedSongs.Count(x => x.IsSelected) == 0)
            {
                ScriptManager.RegisterStartupScript(page, this.GetType(), "script", "publishDialog();", true);
                return View("../Users/UserProfile", uploadedSongs);
            }
            else
            {
                return RedirectToAction("../Home/Index");
            }
        }
2
  • 3
    You seldom need to run client-side script from server-side. The two are completely separate beasts. What is the overall aim you are trying to achieve? Commented Jul 8, 2015 at 14:33
  • Check out this: stackoverflow.com/questions/4994040/… Methinks it has the answer. Commented Jul 8, 2015 at 15:15

1 Answer 1

5

You shouldn't try to register startup scripts like this. Instead you should set a value on your Model that is interpreted by your view logic. Something like this:

var myViewModel = new MyViewModel();
myViewModel.NeedsToRunJs = true; //some logic
return View(myViewModel);

Then in the Razor View:

@if(Model.NeedsToRunJs)
{
    <script>
        /* js to run */
    </script>
}

Or, if you want the javascript to be external, add the src:

@if(Model.NeedsToRunJs)
{
    <script src="someFile.js"></script>
}
Sign up to request clarification or add additional context in comments.

3 Comments

I was hoping for another way if possible rather than putting script in views, rather have them in external js files
then do <script src="someFile.js"><script> instead
also, having view logic in the view is way better than having a javascript function in the controller.

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.