Asp.NET MVC View with different objects - asp.net-mvc

If i have a controller action "Create" that returns a view with the following as the Model type:
public class PaymentModel
{
public Model.SummaryInformation SummaryInformation;
public Model.CardDetail CardDetail;
}
If there is a button on this view that POST's to an action "New" and I want that action to recieve a different object e.g.
public class PaymentNewModel
{
public Model.CardDetail CardDetail;
}
Is this possible? I do not want to use the same Model when the view is rendered to the Model that is POSTed

I'm not aware of anything that would prevent this. The action binder doesn't really care, as long as it can figure it out.
I assume the SummaryInformation object is only used for presentation? (it does not affect the input form?) In that case, you could pass it via ViewData and just bind the view directly against the CardDetail. This is closer to the MVC philosophy, but probably not a huge deal one way or the other.

Related

Need advice on how to structure asp mvc razor page

I have one page that will contain a lot data.
Outline of the page is on the image.
For output I have used "razor" engine.
Now I wonder will I get something if I refactor my code so each section
which data comes from database will be partial view?
On this page I need about 20 value objects to display all needed data.
I have made one "ViewModel" class that contains all data I need and set that
viewModel class as razor page model. Is this the right way how I should do this or
there is some smarter way?
public class MyViewModelClass{
public ValueObjectx x;
public ValueObjecty y;
public ValueObjectz z;
public List<ValueObjectT> tList;
public List<ValueObjectG> gList;
public List<ValueObjectS> sList;
}
In a scenario like this I would typically have each section as a partial view. Each section is responsible for it's own layout and ViewModel. This prevents the tendency to have a super view which has to know about too many things in order to render.
I would not use one ViewModel for all the data. I would only use the ViewModel for the data that might actually be posted back to the server. For all the other data, like lists, I would put it on the ViewBag. Like:
public ViewResult SomeAction()
{
var model = GetYourModelData();
ViewBag.TList = GetTList();
ViewBag.GList = GetGList();
ViewBag.SList = SList();
return View(model);
}
You could put all the lists in a separate helper object if you use them a lot.
Note that this is not a "this is how you should do it answer", it is more a description of what works for me. But as I see it the model of the view is one thing and the actual data, as data in drop downs etc., on the view is another thing and should be put in the ViewData property, but the ViewBag is just a dynamic wrapper around the ViewData property. You can then use the properties on the ViewBag as input to your partial views that should make up each of your sections.

Show partial view based on parameter

In the process of updating a C# MVC 2.0 application!
I have a view “Signup” and another view “ForgotPassword”.
Each view have a with a submit button.
Each form is submitted to the same Controller but to two different ActionResult:
[HttpPost]
public ActionResult Signup(SignupModel signupModel)
{…}
[HttpPost]
public ActionResult ForgotPwd(ForgotPasswordModel forgotPasswordModel)
{…}
Upon completion my goal is to redirect the user to a “thankyou” page but based on where the user is coming from (either Signup or ForgotPassword) I wish to display a particular message (or a different UI).
Inside the same Controller, I created a “Thankyou” ActionResult:
public ViewResult Thankyou()
{
return View();
}
I was thinking of adding a parameter to my Thankyou() method which would allow me to know where the user is coming from (Signup or ForgotPwd). From there, make the “thankyou” page display the appropriate UI/message.
I’m looking for a clean and simple solution.
Should I create two View User Controls and show the appropriate one based on the parameter being passed?
In addition, instead of having an “ActionResult” for my Thankyou() method couldn’t I use a “PartialViewResult” ?
EDIT:
I was actually considering something along those lines…
Where ThankyouType is an Enum.
[HttpPost]
public ActionResult Signup(SignupModel signupModel)
{
//Validation code...
return View("Thankyou", ThankyouType.SignupDone);
}
[HttpPost]
public ActionResult ForgotPassword(ForgotPasswordModel forgotPasswordModel)
{
//Validation code...
return View("Thankyou", ThankyouType.ForgotPasswordDone);
}
And then have my “Thankyou” ViewResult like this:
public ViewResult Thankyou(ThankyouType type)
{
return View(type);
}
Doesn’t seem like I can create a strongly typed view based on Enum (unless I’m wrong).
Perhaps I’ll read more on PartialViewResults and/or find examples…but then again, I could be completely wrong.
I would personally give the ThankYou view a model that has the message you want to display, and have your two controller actions render the ThankYou view directly on success rather than calling a ThankYou action.
However, if you're sure you want a redirect, you may consider using the TempData collection to store a message or a key of some kind. The ThankYou controller can then retrieve this value and pass it to the View. This situation is what TempData was made for.
Edit
There's no reason you shouldn't be able to use an enum value as your model type, but if that gives you trouble you should at least be able to create a model type that has an enum property on it.
The strategy of sending the ThankYouType as part of the redirect request would work just fine, if that's what you prefer. The only potential downside is that it would look like this in the URL:
http://domain.com/controller/ThankYou?type=ForgotPasswordDone
I have no real arguments against it. There are lots of options. Use the one that feels best to you.

Should a model contain all of the data required to build the view?

Lets say I have a site that has a Layout with navigation. This navigation is built each time a page is requested based on options the user has chosen. This navigation does not really have anything to do with the particular view being presented except that it is required for the Layout. The question is, should this be put in the ViewData or should the Model be required to inherit a NavigationModel?
ViewBag.NavItems = navItems;
or
public abstract class NavigationModel
{
public List<NavItem> NavItems { get; set;}
}
public class HomeModel : NavigationModel
{
}
This sounds like an ideal case to use Html.RenderAction inside of the view to render the navigation. This would call an action on a NavigationController that would be responsible for rendering the menu directly into the view.
Some MVC purists feel that Html.RenderAction breaks true MVC architecture; I see it as a way of delegating responsibility to render certain parts of the view that are not the primary responsibility of the "main" view that you're rendering.
Should a model contain all of the data required to build the view?
Absolutely and definitely YES.
The question is, should this be put in the ViewData
Absolutely and definitely NO.
You also have the possibility of using Html.Action and Html.RenderAction if this navigation widget could be considered as fully independent part of your site.

Problem with strongly typed partial view

I've a problem with Partial View.
I am developing a blog in asp.net mvc and I would make in my masterpage a list of categories, last post, last comments.
I think that the best solution is to use strongly typed partial view, and in each partial view pass the necessary model.
MY problem is that the model in View.. in any view (connected to the masterpage's contentplaceholder) enter in conflict with the models in partial views and I get an error like this:
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[Blog.Models.Articoli]' but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[Blog.Models.Categorie]'.
I found on web a dirty solution that consist of to pass togheter the model of any view, some viewdata, one for every model to pass in partial view. But this solution don't respect DRY Principle..because you must repeat this code for each action!
So, my question is: Can I create a model that contain also partial view's model?
If, yes, in that way?
It Exist another solution more simple?
Thanks for help
How about the View Model Pattern?
I've created wrapper classes that are passed to my views rather than whatever object I would normally use
public class MyCreateUserView
{
public User CreatingUser { get; set; }
public MyPartialViewObject Blah { get; set; }
}
In your view write:
public ActionResult CreateUser()
{
MyCreateUserView createUser = new MyCreateUserView()
{
CreatingUser = GetUserFromSomewhere(),
Blah = GetPartialViewObject();
}
return View(createUser);
}
Then your page header looks like so:
<%# Page Language="C#" Inherits="ViewPage<MyCreateUserView>" %>
and when you render your partial write:
<% Html.RenderPartial("../MyPartialViewObject ", Model.Blah); %>
Instead of solving that with the pattern you describe (which is generally a great pattern), I solve that with calls to RenderAction and have it return a partial view. That way the code is in one place as each call to each view does not have to worry about marshalling all the data you need. If you want to see a short discussion on how to use it, I would check Haack's blog here: http://haacked.com/archive/2009/11/18/aspnetmvc2-render-action.aspx. You can also check out the discussion on this other post here on SO: ASP.NET MVC Master Page Data

Can I return an edited object back to Controller from my strongly-typed View without having to use Request.Form?

Just wondering, I strongly type these views in ASP.NET MVC and then use Request.Form on the submit controller to get the data out, validate it, put it in an object, send to database. Is there a way I can just send the object back from the View page since it is strongly typed instead of doing all this crap to just end up with an object again since I just started with one anyways?
You mean, model binding?
[AcceptVerbs (HttpVerbs.Post)]
public ActionResult UpdateUser (User user)
{
SaveUpdates ();
return View();
}
This will automatically initialize the User properties with the form values with the same names.
Look at this answer: ASP.Net MVC Custom Model Binding explanation
(source: odetocode.com)

Resources