问题
I am developing an MVC application. I want to call a javascript function on page load event of a page. Also I want to pass some string parameters to this function which i want to show as confirm message content. On confirm's OK click, i want to show an alert. How can i do this?
Thanks, Kapil
回答1:
If you're thinking about traditional ASP.NET server side Page_Load events then forget about it. Rather use something like jQuery and have a js function execute client side. You can pass in the params you want directly to the js.
回答2:
In ASP.NET MVC project, the codebehind files(view.aspx.vb or view.aspx.cs) are not present. So first you'll need to add the code behind files as follows :
- Add new class(with same name as your view & vb extension) (e.g User.aspx.vb).
- Import
System.Web.Mvc
assembly to your class file. - Inherit your class from ViewPage.
Go to your aspx page(view page), and edit it as follows :
<%@ Page Title="" Language="VB" MasterPageFile="~/Views/Shared/Site.Master" Inherits="MvcApplication2.User" CodeBehind="User.aspx.vb" %>
- In order to attach code behind file with View, select both files ->right click->Exclude from Project. Then click Show All Files in Solutino Explorer Window. Again select these two files->right click->Include in Project.
- Add Page_Load even in your code behind file.
Your code behind file looks as follows:
Imports System.Web.Mvc
Public Class User Inherits ViewPage
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
MsgBox("page Loaded")
End Sub
End Class
回答3:
In your view, simple code your alert() call in the appropriate place. You can build up the string to display using parameters from your Model passed to the view. Your controller will update this view with the data to display. You will probably want to create a strongly-typed view to do this. If this sound unfamiliar to you, please review the "nerd dinner" tutorial or scottgu's blog.
来源:https://stackoverflow.com/questions/2206153/invoking-a-function-on-page-load-event-in-mvc