MVC3: How to Post a Form that contains partial views? - asp.net-mvc-3

Tools: MVC3, jQuery Unobtrusive Validation, Razor, VS 2010
I am developing an MVC2 project that enables users to request services. I have placed information common to all forms in partial views, which are strongly typed to their own models. Each partial view has its own controller. The partial views are rendered in the main container page. I have unobtrusive jQuery data validation working for all data on the rendered page.
Questions: What is the best way to code a Post that relays all the page data to the server and how can I associate the partial views to their respective models? Is it possible for the controllers for the partial views to handle their own data storage chores? Any good examples somewhere? Or, is this architecture flawed and I should rethink?
Thanks in advance,
Arnold

No, not at all, sounds nicely broken up and easy to test. First off, make sure the forms are well set up with the right action, method, etc. in HTML. So then to post the whole page you could do something like this:
var savePage = function () {
$('form').each(function (formIndex, formElement) {
var f = $(formElement);
$.post(f.attr('action'), f.serialize(), successfulFormPost);
});
};
var successfulFormPost = function (data) { ... };
Now, if your MVC view looks something like this:
(Notice the naming convention for the name attribute). Then you can make your controller for that form take in a strongly typed parameter that matches the view's #Model:
public class SomeModel {
public int Id { get; set; }
public string Description { get; set; }
}
public class SomeController : Controller {
[HttpPost]
public ActionResult SomeAction(SomeModel someModel) {
// use someModel.Id, someModel.Description here
}
}
I did that HTML a little more manually, but I'm just proving a point about binding and linking up HTML POST with controller actions. I'll leave it up to you to bring in unobtrusive validation by using the Html.TextBox type syntax. Just remember to set the name attribute of your input fields according to how the default binder works:
http://www.asp.net/mvc
That's a great source for all these fundamentals.

Related

How to display a fully formed HTML page as an MVC view?

MVC/ASP.NET/C#/html/javascript newbie question:
I'm trying to move some legacy software into an MVC solution. I have an MVC controller ViewResult method that makes an API call to the legacy system and returns a string which is a fully formed HTML page (including the HTML start and end tags). Some time in the future, I'll rewrite the logic as an MVC view, but for right now I need to just display that page (preferably in a new tab).
I've tried this in the controller:
return View((object)calendar);
(where "calendar" is the string containing the HTML document)
In my view I have
#model string
#{ Layout = null; }
#Model
But that didn't work.
Any ideas?
Model binding is binding the object of your model class.
For example, ([Solution].[Models].[Model class]),
#model PassDatainMVC.Models.Record
To pass the data from controller to view,
Approach 1: ViewBag
Controller:
string data = "testing";
ViewBag.see = data;
return View();
View:
#using PassDatainMVC.Models
#ViewBag.see
Or:
Approach 2: Model binding
Controller (Class):
public string recordProperty;
View:
#model PassDatainMVC.Models.Record
#Model.recordProperty
While you have to set the property under the model class in the data field for the second approach.
Ref. https://www.c-sharpcorner.com/article/asp-net-mvc-passing-data-from-controller-to-view/
If you want to just one data you can use a ViewBag. This is simple.
Also you want to send with model. You should use this code.
Class
public class Calendar
{
public string CalendarName { get; set; }
}
Controller
Calendar newModel = new Calendar();
newModel.CalendarName = "test name...";
return View(newModel);
View
#model ModelNamespace.Calendar
<h1> #Model.CalendarName </h1>
Thanks Reha! But unfortunately neither of your suggestions did the trick.
For your first suggestion I used ViewBag. In the controller I replaced
return View((object)calendar);
to
ViewBag.calendar = calendar;
return View();
And replaced the view with just
#{ Layout = null; }
#ViewBag.calendar
The result was that the user is left looking at the actual HTML code instead of what the HTML code is supposed to render.
For your 2nd suggestion, I did exactly as you suggested (except I changed
Model.CalendarName = "test name...";
to
Model.CalendarName = calendar;
The result is the same, the user is left looking at the HTML code.

Constructing HTML in Controller - how to refactor?

I'm currently generating breadcrumbs on an object's Details page by calling a GetBreadcrumbs() method in the object's controller - in this method, the object's parent/grandparent are used to generate an unordered list. What's the best way to pull the HTML out of the controller to follow the Separation of Concerns paradigm? Should a partial view be used here?
Typical example of partial view is Breadcrum itself. For example, in your controller you can have
//
//GET: News/Article/x
public ActionResult Article(int id)
{
//get parentid of article
ViewBag.id = id;
ViewBag.parentid;
return View();
}
So, your partial view will be as below:
#{
ViewBag.Title = "Article";
}
<h2>Viewing Article #ViewBag.parentid >> #ViewBag.id</h2>
You could use partial views or display templates. Your controller should only build the model that will be passed to the view and then inside the view you could use a display template that will build the desired output based on the model.

How can we include a form in _layout?

I currently have a _layout.cshtml used by every page of my website.
I need to put a form on each page displayed as a popin.
So, i created a new PartialView (the content of my form) with its corresponding ViewModel and called it in _layout.cshtml.
However, i have a model conflict between ViewModels of pages using the layout and the ViewModel used by the new form (since we can't have directly two models for the same view).
The model item passed into the dictionary is of type 'XXX', but this
dictionary requires a model item of type 'YYY'.
How can we include a form in _layout without this conflict ?
The following has worked for me with a sidebar on every page.
Create a controller for your partial view
In that controller, create a method for the view you want to return, and be sure to use the [ChildActionOnly] filter
public class PartialController : Controller
{
[ChildActionOnly]
public PartialViewResult Alerts()
{
return PartialView("Alerts", messages);
}
}
In your _layout view, you'll have the following:
#Html.Action("Alerts", "Partial")
(instead of #Html.RenderPartial or #Html.Partial)
It sounds like you already have what you need for the view.
I have not used this with a form, but it should work similarly. Hope this helps.

HTML markup & ASP.NET MVC3

I have parts of the web page which I would like MVC3 to serve to client pages. Instead of making them static in everysite. I have sites which have reoccurring markup in parts in the page, such as banner, navigation. In some sites I will need to customize the markup a little. So I need to be able to extend if possible.
Can someone please tell me if MVC3 is ideal as a solution to this? I am thinking partial views. Can you inherit & extend partial views?
Thanks
Partial Views can be implemented for your needs. For example, you can use them as follows :
#model string[]
#if((bool)Model[0]) {
<span>I like it to be this way.</span>
} else {
<span>No, I like it to be that way.</span>
}
Inside a view, you can call this partial view as follows :
#Html.Partial("myPartialView", new string[] { "true" })
You can pretty much pass anything to partial view as Model.
If you plan to use those partial views on multiple applications, I encourage you to create Nuget package for those Partial Views and get them into each application through Nuget Package Manager.
Banners, navigation, custom panels etc - all these are the components that you might want to add, combine, remove or update as time goes. Yes, partial views would do the job easily, but in my opinion, inheritance isn't a way forward.
Your partial views should be based on view models. For example: OrderPanelViewModel, UserMenuViewModel, CustomPanelViewModel. Each partial view is now a component, a feature that you can add,remove, modify as you feel suited.
What happens if you want to combine banner and a user menu? It's not going to work if they inherit from the same view model, but it will work if they have their own view models.
For example:
public class MyCustomPaneViewModel{
public UserMenuViewModel UserMenu { get; set; }
public UserBannerViewModel UserBanner { get; set; }
}
You can now base your view on this view model
#model YourDll.WebUI.Models.MyCustomPaneViewModel
#section main_content{
#Html.DisplayFor(model => model.UserMenu, "UserMenu")
#Html.DisplayFor(model => model.UserBanner, "UserBanner")
}

Loading multiple controls in ASP.NET MVC

I am creating my first site in asp.net MVC and I have a very beginner question in my mind. i have seen that in controller we are returning the actionview for what we want to display in the page [Most of the example in the websites I can see they are only displaying the content in the page] . What if I have to load 3 drop down list, 2 tables , 2 radio buttons etc. What is the best practice and the correct way to load these many controls on the page?
Chris
It sounds like you are expecting to use controls like one does in ASP.Net Web Forms. However, with MVC the View consists of standard HTML. The controls you mention can just be input select and so on. There are various helper classes and methods that you can use in the view to help you render the HTML you need - In particular take a look at the Razor syntax.
I'd start with looking at a couple of examples, and it should be clearer....
Here's a good one: http://www.nerddinner.com/ (source code here http://nerddinner.codeplex.com/)
Maybe pick up a couple of books from Amazon as well.
HTH
Phil
The examples you typically see use MVC's scaffolding, which creates a very simple Controller/Actions/Views to manipulate a certain Model class. But you're free to show anything you want in your pages. Here's an example on how to show a drop down list.
First create an object that will hold all the stuff you want to display on the page:
public class GameDetailsViewModel
{
public Game Game { get; set; }
public SelectList Players { get; set; }
}
Note the SelectList. It will be used as the source for the DropDownList.
Then the Action fills in this object:
public ViewResult Details(int id)
{
GameDetailsViewModel viewModel = new GameDetailsViewModel();
viewModel.Game = db.Games.Single(g => g.ID == id);
IEnumerable<Player> players = db.Players();
viewModel.Players = new SelectList(players, "ID", "FullName");
return View(viewModel);
}
Note the overload to the View() method, that takes the object we created to package the stuff we need on the page.
Then on the View, you can use an HtmlHelper to render a DropDownList:
#using (Html.BeginForm("signup", "games", FormMethod.Post))
{
#Html.DropDownList("playerID", Model.Players, "Select...", null)
<input type="submit" value="Sign up" />
}
This is a very simple example, but you can extend it to send whatever you want to the View and then render it using plain old HTML or the handy HtmlHelpers.

Resources