Mariusz K.
Mariusz K.

Reputation: 53

Mvc and Web forms. How to send data between them?

I’m working on MVC project and I have to use web forms control there. I can include whole page in iframe in my mvc project view that’s not a problem. That kind of behavior is acceptable. But I have a problem with data I need to exchange. I want to send some data from the controller there and also get some response after control end its work. To be more specific:

1. Send some initial values to the web control from controller on start.
2. Something like “magic” button in web forms when it’s clicked I have post back to the controller with some data generated by the control.

Is this even possible?

Upvotes: 4

Views: 4186

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

This certainly is possible. You could use an iframe to host the legacy WebForm inside the ASP.NET MVC application. Let's suppose for example that you have the following ASP.NET MVC controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.ValueFromMvc = "this value is coming from MVC";
        return View();
    }

    public ActionResult Back(string valueFromWebForms)
    {
        return Content(string.Format("This value came from WebForms: {0}", valueFromWebForms));
    }
}

with the corresponding ~/Views/Home/Index.cshtml view:

<iframe src="@Url.Content("~/webform1.aspx?value_from_mvc=") + @Url.Encode(ViewBag.ValueFromMvc)"></iframe>

and the following ~/WebForm1.aspx:

<%@ Page Language="C#" %>

<!DOCTYPE html>
<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            label.Text = Request["value_from_mvc"];
        }
    }

    protected void Link_Click(object sender, EventArgs e)
    {
        var httpContext = new HttpContextWrapper(Context);
        var requestContext = new RequestContext(httpContext, new RouteData());
        var urlHelper = new UrlHelper(requestContext, RouteTable.Routes);
        Response.Redirect(
            urlHelper.Action(
                "Back", 
                "Home", 
                new { valuefromwebforms = "coming from WebForm1.aspx" }
            )
        );
    }
</script>


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Label ID="label" runat="server" />
        <br/>
        <asp:LinkButton 
            runat="server" 
            ID="link" 
            OnClick="Link_Click"
            OnClientClick="document.forms[0].target='_top';"
            Text="Click here to send a value back" 
        />
    </form>
</body>
</html>

In this example I supposed that the WebForm is part of the MVC application which allows us to use helpers to generate the links between them. Of course if this is not the case you must use absolute urls to link between the 2 applications.

Upvotes: 6

Related Questions