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

Im working on an MVC project, and I have to use web form controls there. I can include the whole page in an iframe in my mvc project, this is not a problem. This behavior is acceptable. But I have a problem with the data that I need to exchange. I want to send some data from the controller there, and also get some response after the control finishes its work. To be more specific:

1. Send some initial values ​​to the web control from the controller at startup.
2. Something like a β€œmagic” button in web forms when you click it. I go back to the controller with some data generated by the control.

Is it possible?

+4
source share
1 answer

It is certainly possible. You can use an iframe to place the inherited WebForm inside an ASP.NET MVC application. 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 view ~/Views/Home/Index.cshtml :

 <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 assumed that WebForm is part of an MVC application that allows us to use helpers to create relationships between them. Of course, if this is not the case, you should use absolute URLs to communicate between the two applications.

+5
source

Source: https://habr.com/ru/post/1439405/


All Articles