Search code examples
asp.net-mvcasp.net-mvc-3asp.net-mail

Email a Friend functionality in MVC


Pretty much there would be an icon on the site. clicking it would bring up a pop up window with following fieds:

  1. Name
  2. Email

you would then be able to fill out the page and an email would be sent to "email" provided in the "Email" field. The problem is: How do i know what page i'm on so that I can put it in the message? thanks


Solution

  • @ViewContext.RouteData.GetRequiredString("action")
    @ViewContext.RouteData.GetRequiredString("controller")
    

    should contain the current controller and action which you could use. you could also extract other route parameters like:

    @ViewContext.RouteData.Values["id"]
    

    So this information could be posted to the controller action that is going to send the email:

    @using (Html.BeginForm(
        "Send", 
        "Email", 
        new { 
            currentAction = ViewContext.RouteData.GetRequiredString("action"), 
            currentController = ViewContext.RouteData.GetRequiredString("controller") 
        }, 
        FormMethod.Post)
    )
    {
        <div>
            @Html.LabelFor(x => x.Name)
            @Html.EditorFor(x => x.Name)
        </div>
        <div>
            @Html.LabelFor(x => x.Email)
            @Html.EditorFor(x => x.Email)
        </div>
        <input type="submit" value="Send email!" />
    }
    

    And the action that will send the email:

    public ActionResult Send(string name, string email, string currentAction, string currentController)
    {
        // TODO: based on the value of the current action and controller send
        // the email
        ...
    }