how to display using asp.net mvc - asp.net

I have a partial view called StudentInfo.ascx. In it I have something like this:
<fieldset>
<legend>Students Information</legend>
<div>
<label>First Name:</label>
<label>Last Name:</label>
</div>
</fieldset>
I have another partial view called Detail.ascx which will need to display this StudentInfo.ascx. I did something like this:
<%= Html.RenderAction("StudentInfo"); %>
Is that right?

It depends on what you intend to do and if you use strong type views etc... By the info you provided it would be better to use RenderPartial() but your partial view doesn't make any sense the way it is. It lacks significant details.
RenderPartial vs. RenderAction
If you use Html.RenderPartial(), it will work faster, but you will have to provide the data for your partial views in a single controller action that returns the parent (partial)view.
If you use Html.RenderAction() it will work slower, but it gives you more flexibility and decoupling from the parent (partial)view, because data for a particular child partial view will be provided by always the same controller action that's completely independent of parent (partial)view and controller action that returned it.
How to choose
Both are correct. It all depends on the problem at hand.
If your partial views are not strongly typed and/or they are meant for posting you will most probably display them using RenderPartial() extension method.
But if they do consume some data and they are strongly typed and they are used on multiple completely different views it's probably much better to use RenderAction().
Think of RenderPartial() as a placeholder that just renders some view and RenderAction() as a separate MVC request pipeline. So before partial view gets rendered the whole request pipline is executed:
request gets issued
controller action gets invoked, prepares data and
returns a partial view (that will be placed inside some other parent (partial)view)
So much more overhead.

Try
<% Html.RenderPartial("StudentInfo") %>

Related

Models Interfering with Partials

So currently in my _Layout file, I have a global login and Register system which will show on every page:
<div id="global_login_register">
<div id="login">
#Html.Partial("_LoginPartial")
</div>
<div id="register">
#Html.Partial("_RegisterPartial")
</div>
</div>
#RenderBody()
In my loginPartial page I have a #model LoginModel and in my register I have #model RegisterModel. So far everything works, but the problem is when I try to submit another model to the View() it's interfering with the login partials. Is the only way to fix this is to use the ViewBag and save my model onto there?
If your partial needs a model, you need to pass it with the partial call: #Html.Partial("_LoginPartial", aLoginModel). The harder question is where to get aLoginModel, and there are a few possible options...
Use #Html.Action(...) to defer to a separate control (that can build a LoginModel for you) - generally not worth the overhead of a full controller lifecycle, but it's a clean solution if you can afford it.
Use an interface for your LoginModel and require that every view model implement it - almost certainly not a good idea, but it would work.
Store the LoginModel in ViewBag/ViewData using some mechanism that's guaranteed to execute before your views will be rendered.
Write your own Html helper that knows how to build the LoginModel from the HtmlHelper context. You could either use that result in the _layout (e.g. #Html.Partial("_LoginPartial", Html.LoginModel)) or put the Partial call inside the helper (e.g. #Html.Login()).
For anything performance-critical, I would use #4.

Implementing simple CRUD with OpenRasta and Web Forms

I've been asked to look into OpenRasta as an alternative to MVC ASP.NET at work, and as a starting point I'm trying to replicate the Movies tutorial from the MVC ASP.NET website.
I really like the ReST style of OpenRasta, and so far have got a simple database and a handler for GET based by ID, in the form of
ResourceSpace.Has.ResourcesOfType<Movie>()
.AtUri("/movie/{id}")
.HandledBy<MovieHandler>()
.RenderedByAspx("~/Views/MovieView.aspx");
I understand that use of POST and DELETE would allow me to create/update and delete items from my database, but unfortunately I'm stumped on how to do the views.
In the OpenRasta documentation it says:
When you use an aspx page as a view in OpenRasta, you essentially create a template to
generate content. As such, postbacks and events are not supported.
I might be being really dumb here, but would I be able to POST and DELETE from an ASP.NET page in the manner required by OpenRasta? I'm using a code-behind page, but that's not something I'm fixated upon.
I'm not that familiar with ASP.NET (haven't done any for ages), so I may be missing something obvious, but would really appreciate some pointers in the right direction.
What this means is that the postback model in asp.net webforms (aka the behavior by which the asp.net webforms infrastructure creates one massive form tag to post back asp.net specific data to a page continuously) is not supported, so any events you may be used to use on webforms controls will not work.
If you're used to MVC-styled interactions, you know how to use the form tag so you do as usual to create a new movie.
<form method="post">
<fieldset>
<input type="text" name="Name" />
<input type="submit" />
</fieldset>
The alternative is to do it in code using the webforms engine
<% using(scope(Xhtml.Form<Movie>().Post())) { %>
<%= Xhtml.TextBox<Movie>(_=>_.Name) %>
<% } >
And your handler code
public Movie Post(Movie movie) {
// create the movie instance in your db or whatever
return new OperationResult.SeeOther { RedirectLocation = movie.CreateUri() };
}
Code compiles in my head and may need a reality check before being put in a compiler.
Note that it's probably a good idea to move away from the webforms engine if you can, there are better alternatives (razor, spark, whatever you may decide to plug in).

ASP.NET MVC3 Partial View naming convention

I'm new to the MVC development so please bear with me. Is it really necessary to name my partial view like _Action.cshtml (with the _ underscore) to comply with the naming convention?
Here's my problem I have a controller (StudentController) and an action (List) that has a partial view file named "List.cshtml", and have
#{ Html.RenderAction("List", "Student"); }
to display this inside my HomeController - Index view as partial view which works. But if I name my partial view to _List.cshtml of course it will not work. Visual Studio could not even find the view for my action Student - List because it think it's still looking for the exact same name as my action (List.cshtml). What should I do?
I m so used to ASP.NET ascx with a pairing ascx.cs code. :(
It's not necessary to use an underscore, but it's a common convention for files which aren't meant to be served directly.
To solve this, you do have the option of returning a View or PartialView with the name of the view as a parameter.
return View("_List");
or
return PartialView("_List");
or inside another view
#{ Html.RenderPartial("_List"); }
If Partial view depends on ActionMethod and always render by Action method, you should same partial view name same as action method like this
public PartialViewResult List()
{
DoSomthing();
//PartialView() return a "List "Parial View
return PartialView();
}
but if your partial view not depends on the action method and directly call by view like this
#Html.RenderPartial("_List");
First, there is no shame to be new to any platform. And this was eight years ago so you are probably not new any more. You can use whatever naming conventions you want to use. I go with the original MVC naming convention which uses underscores (_) only for shared views. Partial views should be named after their actions. In your case the name of the view would be Action.cshtml unless this is a shared view of course.
My reasoning is simple. If you call View or PartialView from an action and don't provide a viewName, it assumes the name of the view is the name of the action. Also _Layout.cshtml is named with an underscore. This is because it is shared, not because it is a partial view. This mistake is all over the place in the MVC world. People are really zealously wrong about it. Don't know why. Naming convention is the shop's discretion.
The helper methods Html.RenderAction and Html.Action call actions on the controller. The helper methods Html.RenderPartial and Html.Partial allow you to pass a model directly to a Razor view without passing through an action.
One final thing, call Action instead of RenderAction. RenderAction is only called if you are already inside of a code block. This is almost never the case. I see people using RenderAction and then adding a code block around it unnecessarily just because the build breaks. These two following code snippets are exactly the same and the second one is way more readable in my opinion. I put the div to emphasize that the code is not in a code block:
<div>
#{ Html.RenderAction("List", "Student"); }
</div>
<div>
#Html.Action("List", "Student")
</div>
The bottom line is don't use underscores or curly braces unnecessarily. They are ugly characters and we should avoid them. ;)

ASP MVC: Submitting a form with nested user controls

I'm fairly new to ASP MVC so go easy :).
I have a form that contains a number of user controls (partial views, as in System.Web.Mvc.ViewUserControl), each with their own view models, and some of those user controls have nested user controls within them. I intended to reuse these user controls so I built up the form using a hierarchy in this way and pass the form a parent view model that contains all the user controls' view models within it.
For example:
Parent Page (with form and ParentViewModel)
-->ChildControl1 (uses ViewModel1 which is passed from ParentViewModel.ViewModel1 property)
-->ChildControl2 (uses ViewModel2 which is passed from ParentViewModel.ViewModel2 property)
-->ChildControl3 (uses ViewModel3 which is passed from ViewModel2.ViewModel3 property)
I hope this makes sense...
My question is how do I retrieve the view data when the form is submitted? It seems the view data cannot bind to the ParentViewModel:
public string Save(ParentViewModel viewData)...
as viewData.ViewModel1 and viewData.ViewModel2 are always null. Is there a way I can perform a custom binding?
Ultimately I need the form to be able to cope with a dynamic number of user controls and perform an asynchronous submission without postback. I'll cross those bridges when I come to them but I mention it now so any answer won't preclude this functionality.
Many thanks.
For databinding to work you need to give special names to your text fields. For example in ChildControl1:
<%= Html.TextBox("ViewModel1.Property1", Model.Property1) %>
This will generate the following markup:
<input type="text" name="ViewModel1.Property1" id="ViewModel1_Property1" value="" />
And when you post to the following action:
public ActionResult Save(ParentViewModel viewData)
{
...
}
It will update the value of viewData.ViewData1.Property1. For binding collections you may take a look at this article.

ASP.NET MVC ViewResult vs PartialViewResult

What is the difference between the controller result named ViewResult and PartialViewResult? More importantly, when is the PartialViewResult used?
PartialViewResult is used to render a partialview (fx. just a user control). This is pretty nifty for AJAX stuff, i.e.
<script type="text/javascript">
$.get(
"/MyController/MyAction",
null,
function (data) { $("#target").html(data) }
);
</script>
and action
public ActionResult MyAction()
{
return PartialView("SomeView");
}
where SomeView is a MVC User Control, e.g.:
<div>
<%= DateTime.Now.ToString() %>
</div>
http://msmvps.com/blogs/luisabreu/archive/2008/09/16/the-mvc-platform-action-result-views.aspx
In practice, you’ll use the
PartialViewResult for outputing a
small part of a view. That’s why you
don’t have the master page options
when dealing with them. On the other
hand, you’ll use the ViewResult for
getting a “complete” view. As you
might expect, the Controller class
exposes several methods that will let
you reduce the ammount of typing
needed for instanting these types of
action results.
Generally speaking, ViewResult is for rendering a page with optional master, and PartialViewResult is used for user controls (likely responding to an AJAX request).
none of the existing answers actually answer the question "What is the difference".
The differences are as follows:
1) the locations where the view engine will attempt to find the view:
for ViewResult, it's in ViewLocationFormats and MasterLocationFormats
for PartialViewResult, it's in PartialViewLocationFormats
2) ViewResult has the additional property MasterName
that is all.
There are several cases where you would want to break down your view into several small components. One use case that I am working with right now, is I have a multi-lingual site that I would like to reload content using AJAX principles.
Normally what I would do in the case of a non-multi lingual site is to create another ActionResult to return the ViewModel that is changing with the new parameters. I like to use a custom ActionResult that I have called JsonpResult. The problem resides in the fact that I have labels not in my database but in Resource files. So what I would need to do is to somehow hydrate my Resource file data into the ViewModel.
Once the data comes down the pipe, my AJAX callback handles the wiring up of the ViewModel response back to the HTML page using Javascript (I use jQuery).
This definitely works, however it becomes a question of maintainability. I now need to not only maintain my original ASP.NET view, but I also need to maintain a set of scripts that handle AJAXian behavior. If you need to have your site SEO, then you really need to make sure that both the Server Side and Client Side behavior are both working the same.
This is where Partial Views come into play for me. What I do is "pull out" the logical data sections where the bulk of the reload occurs. The nice thing about PartialView is that you can pass your ViewData and Model along to the PartialView. If your PartialView is strongly typed against your ViewModel you can get Intellisense to help with the wiring of the PartialView.
Now all I need to do with my AJAX call is to write the response back to a single DIV rather than handling data points individually. What it does mean is that there would be more content coming down the pipe. However, the trade off is easier to read and maintain code.
The one of the main differences is PartialViewResult doesn't use _ViewStart.cshtml. The code from _ViewStart.cshtml file executes at the start of rendering before any code in the view.

Resources