Monday, September 5, 2011

Using ASP.NET Webform in an MVC controller

In ASP.NET MVC we use controller actions to call views using the following code:

public ActionResult NameOfView()
{
return View();
}

or if we want to pass a view model to it:

public ActionResult NameOfView(model ViewModel)
{
return View(ViewModel);
}

Through this code, the view "NameOfView", placed in the folder "Views", will be displayed (in the second instance the view model will be passed to it as an input parameter).
However if we want to work with an ASP.NET view which is NOT in the folder "Views" but is instead located at "Abc/Def/page.aspx", we can change our controller slightly to accommodate this view. To do this, we can use the following code:

public ActionResult NameOfView()
{
return View("~Abc/Def/page.aspx");
}

or if we want to pass a view model to it:

public ActionResult NameOfView(model ViewModel)
{
return View("~Abc/Def/page.aspx", ViewModel);
}

Adding jQuery to an MVC view

To add jQuery code in an MVC view, we need to write its code in the head section of the view. The example below shows simple jQuery code written in an MVC view.

<head>
<script type="text/javascript">
$(document).ready(function ()
{

// here we can write any javascript code that will be executed as soon as the page loads  

// If we have a dropdown in our page, named as "xyz", and need to write code that executes when it's value is changed to "1", we could do the following:

$('#xyz').change(function ()
{
if ($('#xyz').val() == "1")
{

// over here we can write code that will execute when the value "1" is selected in the dropdown "xyz"

}
else if ($('#xyz').val() == "2")
{


// over here we can write code that will execute when the value "2" is selected in the dropdown "xyz"                

}

});
});
</script>

 <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

</head>