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");
            }
        }
tereško
  • 58,060
  • 25
  • 98
  • 150
sitBy
  • 271
  • 5
  • 19
  • 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? – iCollect.it Ltd Jul 08 '15 at 14:33
  • Check out this: http://stackoverflow.com/questions/4994040/scriptmanager-registerstartupscript-code-not-working-why Methinks it has the answer. – Liz Jul 08 '15 at 15:15

1 Answers1

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>
}
DLeh
  • 23,806
  • 16
  • 84
  • 128