Jaqen H'ghar
Jaqen H'ghar

Reputation: 1879

Invoking a function on Page_load event in MVC

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

Upvotes: 0

Views: 2484

Answers (3)

No Refunds No Returns
No Refunds No Returns

Reputation: 8346

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.

Upvotes: 0

H Sampat
H Sampat

Reputation: 1029

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 :

  1. Add new class(with same name as your view & vb extension) (e.g User.aspx.vb).
  2. Import System.Web.Mvc assembly to your class file.
  3. Inherit your class from ViewPage.
  4. 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" %>

  5. 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.
  6. 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

Upvotes: -1

UpTheCreek
UpTheCreek

Reputation: 32391

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.

Upvotes: 1

Related Questions