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");
}
}
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>
}