ASP.NET MVC ViewManager equivalent - asp.net-mvc

I'm looking into ASP.NET MVC, and whether or not to make the switch. One thing that I do a heck of a lot in ASP.NET, is to render HTML on AJAX callbacks and sent back to the client. I use a generic ViewManager for rendering User Controls.
I created a sample MVC App from the templates, and was looking for the RenderUserControl method inside a Controller. I found: System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial but that doesn't seem to be what I'm looking for in this context.
Is there an equivalent to the ASP.NET ViewManager in MVC?

What you want to do is return a partial view:
public ActionResult IWillCallThisViaAjax()
{
return PartialView("MyUserControlName");
}

Related

ASP.NET MVC to PHP Laravel Migration: Html.RenderAction Alternative

I'm currently developing a CMS using PHP Laravel (5.4) based on an existing ASP.NET MVC version I've made in the past. Since most of the ASP.NET version is written in JS, I'm trying to reuse the most I can in the newer Laravel version I'm developing. I have already translated most of the C# code to PHP, thanks to Laravel's similarities with ASP.NET MVC architecture, this was somewhat straightforward.
Currently I'm facing a issue trying to call a controller action from within a view that will in-turn render a partial view. In the ASP.NET MVC version I've accomplished this using a Html.RenderAction helper.
ASP.NET MVC Example:
<div>
#{Html.RenderAction("Controller", "Action");}
</div>
I want know if there is any alternative to the Html.RenderAction helper that I can use to accomplish this task.
I've search the interwebs and Laravel's documentation, and from what I was able to find, View Composers seem to be closest alternative. Unfortunately, I didn't find any example that could resolve my issue.
#Farrukh suggested using View Composers and it does actually work as intended. The problem is that I will need to add a View Composer to the AppServiceProvider for every partial view I want to render.
I found another solution that allows me to call an action from a view and render a partial view:
<?php echo \App\Http\Controllers\PageController::listAll(); ?>
But this solution doesn't seem very clean.
ViewComposer behaves like a global component, all you have to do is put your business logic into a method in your Model.
e.g.
class Post extends Model {
public static function archives() {
return static::selectRaw('your query here')
->get()
->toArray();
}
}
Then goto providers/AppServiceProvider.php
add your viewcomposer code into boot method (a hook before any view loads).
e.g.
#include('layouts.sidebar')
in AppServiceProvier, boot method:
public function boot() {
view()->composer('layouts.sidebar', function($view) {
$view->with('archives', \App\Post::archives());
});
}
You can use the Service Injection:
<div>
#{Html.RenderAction("Controller", "Action");}
</div>
In Laravel would be:
#inject('Controller', 'App\Http\Controllers\HomeOrOtherController')
{!! $Controller->action() !!}.
With this you will render in the view the content of the view of the action in the controller.

ASP.NET MVC migrating master page - Problems with web control logic

I'm trying to migrate an existing ASP.NET Webforms 3.5 application into an ASP.NET MVC 3 application. That means, I attempt to convert existing .aspx pages with webcontrols and codebehind recpectively with controller logic and razor views.
At the moment I'm focusing on the master page (to get an analogue layout.cshtml for all other razor views).
For example I've replaced controls like asp:Menu, asp:LoginView with partial views and #Html.Action to invoke the controller action, run some code that has been in the codebehind of that masterpage before and return that partial view.
But now I'm getting lost with many web controls of the masterpage that have been set in/visible, depending on the code behind. For example there are two asp:panels in the master page that have been switched in/visible depending on the visited page.
The problem is that in razor views I don't have web controls and in controllers I cannot set attributes/properties (like private int counter;).
Thus I don't know how to carry on...
I hope you have got some ideas or experience with this situation.
Please ask if any information is missing.
You can either set properties of the Model or ViewData in the Controller and then use these in the Razor view with #if
e.g.
On the controller:
public ActionResult Index()
{
ViewBag.Foo = IsThisFoo();
View();
}
In the View:
#if (ViewBag.Foo) {
<p>This is foo</p>
}
else
{
<p>This is bar</p>
}
nb: best practice would be to do it as part of a strongly typed Model for the view

Calling asp.net mvc controller's from normal aspx web form?

i want to make some question about asp.net mvc.
How i call asp.net mvc controller action from normal aspx web form?
Our project is used asp.net mvc framework with visual studio 2008 C#.net.
For eg,i want to use like this in normal aspx web form.
public ActionResult callMvc()
{
return RedirectToAction("Display","TempController");
}
I know it should not using like this way in MVC project,but,we need for some case.
Regards
Indi
You can just use a Response.Redirect with the right url which get routed to your controller in question, I guess in your case, that is:
Response.Redirect("/Temp/Display");
It would be a better idea to use the Url helper to resolve the url for you, that way if your routes change then you don't have to refactor your code. Use this method;
Response.Redirect(Url.Action("Display", "Temp"));
I have never used it in this context before but I believe it should work as expected.
Use following code:
Response.Redirect("~/Home/Index");
Controller/action
In WebForm cs file (class derived from System.Web.UI.Page) use:
this.Response.RedirectToRoute(new { controller="ControllerToRedirectTo", action="ActionToRedirectTo", id=5, SomeOtherActionParameter="Parameter value" });

Can ASP.NET MVC return a javascript response like Ruby on Rails can?

I'm diving into ASP.NET MVC and I'm coming from a Ruby on Rails background. I'm trying to understand how ASP MVC handles AJAX functionality and, after reading some of the tutorials on the ASP website, it appears they implement AJAX functionality very differently. One of the ways that RoR handles AJAX functionality is by returning ruby-embedded javascript code that is executed as soon as it is received by the browser. This makes implementing AJAX really simple and quite fun. Can ASP.NET MVC return a javascript response?
just user
return JavaScript(script)
You would have to execute the java script manually on the View
To be more specific you can make the controller action return type JavaScriptResult
What you are talking about is called javascript generators in the RoR world and there's no equivalent in the ASP.NET MVC world. Here's a blog post that illustrates the basics of implementing a Rails-like RJS for ASP.NET MVC (the blog post uses prototypejs but could be easily adapted to work with jquery).
Here's another approach using jquery:
public ActionResult Foo()
{
return Json(new { prop1 = "value1", prop2 = "value2" });
}
and to consume:
$.getJSON('/home/foo', function(result) {
// TODO: use javascript and work with the result here,
// the same way you would work in a RJS like template
// but using plain javascript
if (result.prop1 === 'value1') {
alert(result.prop2);
}
});
Also worth taking a look at is JsonResult which extends ActionResult. I usually use this when making AJAX requests for data of some sort.

Is there an equivalent to Monorail view components for the ASP.Net MVC Framework?

I make heavy use of View Components in some of the larger applications I've built in Monorail - What is the equivalent approach in ASP.Net MVC for a view component, that can support sections etc.?
Actually you have several options to create the equivalent of a ViewComponent in ASP.NET MVC, depending in the complexity of your component. I use these two approaches which are the more mvc-ish of the options I am aware of.
1:
The simplest thing is to create a ViewUserControl and display it using Html.RenderPartial with the helper. The ViewUserControl is a simple piece of markup with no backing controller (I think you can put a codebehind file if you want).
Optionally, you can pass a model object or the entire ViewData dictionary to the view when calling RenderPartial, like this:
<% Html.RenderPartial("TopBar", model); %>
"TopBar" is an ascx page. This works anywhere, in master pages and in normal views.
2:
If you want your component to have more complicated logic or to access datasources, IoC, etc, then you can use Html.RenderAction which is an extension method found in the Microsoft.Web.Mvc assembly. I am using this out of the mvccontrib distribution. It works like this, you need to create a normal controller with all the logic you need, then create some views and all of these things become your component, for example:
public class AboutComponentController : Controller {
public IRepository Repository{ get; set; }
public ActionResult Detail() {
var lastEvent = Repository.FindAll<Auditoria>().FirstOrDefault();
return View(lastEvent);
}
}
Notice how I have a reference to an IRepository which is going to be injected with IoC (Windsor in my case) and I can do anything a normal controller would do.
Now, in any page (master or normal) where you want to use your component, import Microsoft.Web.Mvc and call Html.RenderAction with the appropriate parameters. This will create a mini mvc pipeline that creates the controller, resolves the view, etc., just like a Monorail ViewComponent. I prefer to use the lambda based variation of the method, like this:
<% Html.RenderAction<AboutComponentController>(x => x.Detail("a message"));%>
Unfortunately, the only way to pass parameters is to use the method call itself, which in turn must be unique in the controller. Still needs some work to resemble a ViewComponent.
I don't use masterpages or layouts in the views of my components since they are composition elements themselves.
Remember that when using the Webforms view engine, you can have strongly typed views if you like to have intellisense when using the Model variable in code blocks.
The beauty of this is that you can mix view engines with these approaches, I usually create the components in nvelocity and display them in aspx pages, etc.
I now there can be issues with caching of the partial views but I haven't run into any so far. I am sure there are other options (like subcontrollers in mvccontrib) but this is usually enough for simple cases. Of course you can use normal ASP.net components in your aspx view pages but that would be cheating right? hehe. I hope it helps.
Phil Haack blogged about creating areas to group controllers into sub-folders/sections similar to MonoRails.

Resources