How to Use Two Same Model in a View? [MVC4] - asp.net-mvc-4

I'm trying to create a status update page where I want a user to insert status message in Index page and also, I want to show all inserted all status messages in the same Index page.
This is my Model code:
public class Statuses
{
[Key]
public int StatusID { get; set; }
[DataType(DataType.MultilineText)]
[Required]
public string message { get; set; }
}
public class StatusContext : DbContext
{
public DbSet<Statuses> Status { get; set; }
}
And, I used #Html.EditorFor(model => model.message) in the Index.cshtml page.
To show the editor, I used the following model in View.
#model LearnStart.Models.Statuses
However, to show all the status messages below the Multiline TextArea, I think I'm supposed to use the below one.
#model IEnumerable<LearnStart.Models.Statuses>
How to use both model in same view so that I can display both the text area (to insert the status message) and to list all available status messages below it?

First, you should not be passing your entities directly to your view. The recommended best practice is to use View Models, which are models tailored specifically to your view.
Second, when using a view model you can now do this, since it's not tied to your data model entities:
public class MyActionViewModel {
public List<StatusesViewModel> StatusList {get;set;}
public StatusesViewModel CreatedStatus {get;set}
}
Then in your view:
#model MyActionViewModel
#Html.EditorFor(x => x.CreatedStatus)
.............................................
#Html.DisplayFor(x => x.StatusList)
Then you can create two templates, an EditorTemplate and a DisplayTempate:
In ~/Views/Shared/EditorTemplates/StatusesViewModel.cshtml
#model StatusesViewModel
#using(Html.BeginForm()) {
#Html.EditorFor(x => x.Message)
<input type="submit" value="Create Status" />
}
In ~/Views/Shared/DisplayTemplates/StatusesViewModel.cshtml
#model StatusesViewModel
<div>
<span>#Model.Message</span>
</div>
The thing that's nice about using the templates is that they will automatically iterate over your collection.. no foreach or for statement is used. A single EditorFor works on the entire collection, then renders the template based on the type, which in this case translates to StatusViewModel.cshtml

Easy way is to put a list inside Viewbag and show list in View as shown :-
Controller :
Public Actionresult Myaction()
{
.........
Viewbag.data = //bind list of messages here
return View();
}
View :
#model LearnStart.Models.Statuses
.........
.........
.........
#if(Viewbag.data != null){
<table>
#foreach(var item in Viewbag.data)
{
<tr><td>#item.message</td></tr>
}
</table>
}

Related

Unobtrusive validation doesn't work with ViewComponents

I'm implementing a form with ASP.NET Core v3.1.
I have code for a drop-down on a Razor page which looks like this:
<div class="form-group">
<label asp-for="MySelectedItem" class="m-b-none"></label>
<help-text asp-for="MySelectedItem"></help-text>
<div class="input-group">
<select asp-for="MySelectedItem" asp-items="#Model.MyItems" class="form-control"></select>
<partial name="_ValidationIcon" />
</div>
<span asp-validation-for="MySelectedItem" class="validation-message"></span>
</div>
In my model class, I've included a validation rule to ensure that a valid option must be selected. This renders nicely:
Now, I want to genericise this as a View Component so that I don't have to paste this lump of code anytime I want a drop-down. Here is my implementation:
public class DropdownViewComponent : ViewComponent
{
public IEnumerable<SelectListItem> Items { get; set; }
public ModelExpression SelectedItem { get; set; }
public async Task<IViewComponentResult> InvokeAsync(ModelExpression selectedItem, IEnumerable<SelectListItem> items)
{
Items = items;
SelectedItem = selectedItem;
return View(this);
}
}
/Dropdown/Default.cshtml
#model Web.ViewComponents.DropdownViewComponent
<div class="form-group">
<label asp-for="SelectedItem" class="m-b-none"></label>
<help-text asp-for="SelectedItem"></help-text>
<div class="input-group">
<select asp-for="SelectedItem" asp-items="#Model.Items" class="form-control"></select>
<partial name="_ValidationIcon" />
</div>
<span asp-validation-for="SelectedItem" class="validation-message"></span>
</div>
Usage:
<vc:dropdown selected-item="MySelectedItem" items="Model.MyItems"></vc:dropdown>
This code correctly renders the drop-down, but the validation attributes are missing from the rendered HTML. Why?
I'm also not sure how to get the DisplayName from the model expression that I passed to the View Component.
Where have I gone wrong?
Thanks.
Presumably, your validation attributes are on the MyItems property of your parent model, which isn't listed here. E.g.,
public class ParentModel {
[Required]
public IEnumerable<SelectListItem> MyItems { get; set; }
}
As such, the issue is that your view is no longer binding to that model or its MyItems property. Instead, it's binding to the Items property on the DropdownViewComponent model, which doesn't have any validation attributes on it. Those two properties may both be pointing to the same IEnumerable<SelectListItem> object reference, but their metadata is entirely different. As such, ASP.NET Core is correctly displaying the validation attributes associated with the DropdownViewComponent.Items property.
I see this as an unfortunate limitation of view components—but one that's conceptually difficult to reason out of. For more information, see my answer to a similar question I previously posed, How to bind a ModelExpression to a ViewComponent in ASP.NET Core.
That said, given your particular requirements, you can work around this by passing the model which contains the target property to your view component—instead of passing the value of the target property itself—and then relaying that via your view component's view model:
public class DropdownViewComponent : ViewComponent
{
public ParentModel ParentModel { get; set; }
public ModelExpression SelectedItem { get; set; }
public async Task<IViewComponentResult> InvokeAsync(ModelExpression selectedItem, ParentModel model)
{
ParentModel = model;
SelectedItem = selectedItem;
return View(this);
}
}
Note: I would typically create a separate, lightweight view model for your view component, instead of passing your view component object down to its view. But I'm maintaining this structure for consistency with your original code.
You would then be able to bind to the original property in your view component's view, thus maintaining all of the original validation attributes:
<select asp-for="SelectedItem" asp-items="#Model.ParentModel.MyItems"></select>
On first approximation, this doesn't buy you much—and may even defeat your entire reason for pursuing a view component in the first place—as it forces you to operate against a single model. If multiple views with different models want to use this view component, that introduces some problems. You can mitigate these, however, by introducing a layer of abstraction.
There are a few approaches to this, such as establishing an interface, but the one I recommend is to develop a specialized list class which you use to model IEnumerable<SelectListItem>:
public class DropdownList: List<SelectListItem> {
public virtual IEnumerable<SelectListItem> Items { get; } = this;
}
And then working off of that in your DropdownViewComponent:
public class DropdownViewComponent : ViewComponent
{
public DropdownList DropdownList { get; set; }
public ModelExpression SelectedItem { get; set; }
public async Task<IViewComponentResult> InvokeAsync(ModelExpression selectedItem, DropdownList dropdownList)
{
DropdownList = dropdownList;
SelectedItem = selectedItem;
return View(this);
}
}
And, finally, implementing it as follows in your view component's view:
<select asp-for="SelectedItem" asp-items="#Model.DropdownList.Items"></select>
This would allow you to override this class in order to add attributes as needed. E.g.,
public class RequiredDropdownList : DropdownList {
[Required]
public override Items { get; } = this;
}
Note: if you have a need to use a variety of different collections on different view models, and were relying on IEnumerable<SelectListItem> to unify them, this approach won't work. In that case, creating something like an IDropdownList interface makes more sense. Regardless, the concept is virtually identical.

How to add a list<T> to view with a single model

Getting an error while trying to add a grid to my detail page. The error is:
The model item passed into the dictionary is of type 'GridMvc.Html.HtmlGrid1[MyApp.Models.RecipientActivityMetadata]', but this dictionary requires a model item of type 'System.Collections.Generic.List1[MyApp.Models.RecipientActivityMetadata]'.
MVC4 View is a combination of a detail page and a list. I am using a viewmodel that looks like this:
public class FormViewModel()
{
public RecipientMetadata Recipient { get; set; }
public StudentActivityMetadata StudentActivity { get; set; }
public List<RecipientActivityMetadata> RecipientActivites { get; set; }
}
The view top is:
#model MyApp.Models.ViewModels.FormViewModel
and it renders a partial view which contains the list:
#Html.Partial("_grid", Model.RecipientActivites)
and the partial looks like this:
#using GridMvc.Html
#model List<MyApp.Models.RecipientActivityMetadata>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<div>
#Html.Grid(Model).Columns(columns =>
{
columns.Add(c => c.ActCount).Titled("Activity Num");
columns.Add(c => c.ActivityType).Titled("Activity Type");
columns.Add(c => c.FundCode).Titled("FundCode");
columns.Add(c => c.Hours).Titled("Hours");
}).WithPaging(10)
</div>
From Comment to Answer
According to the documentation provided by Grid.Mvc, #Html.Grid uses a partial view _Grid.cshtml. Because your partial view also has same name, the solution is to use a different name for your partial view.

how to display items in view dynamically in mvc4

I want to display items in view in mvc dynamically.
following is the code for displaying records in view
#using MvcWcf.ServiceReference1
#model IEnumerable<WcfService.MyAddress>
<table>
<tr>
<td>#Html.DisplayNameFor(model => model.Address1)</td>
<td>#Html.DisplayNameFor(model => model.City)</td>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.Address1)</td>
<td>#Html.DisplayFor(modelItem => item.City)</td>
</tr>
}
</table>
my requirement how to display items in th and records dynamically
for example <td>#Html.DisplayNameFor(model => model.Address1)</td><td>#Html.DisplayNameFor(model => model.City)</td>
here i wrote address1 and City because i know the fields.
if i don't know the fields how to display that.
also in displaying records
You can create a generic model with this property
public List<GenericItem> items { get; set; }
than you create your generic item with the property you need, like type (textbox, button, ...), text inside and anything you need
public class GenericItem
{
public enum Type { get; set; }
public string Text { get; set; }
[...]
}
than you must create a custom helper (like a custom editorfor) that accepts a generic model and with that model show on screen the appropriate control with what you have inside your model.
https://www.asp.net/mvc/overview/older-versions-1/views/creating-custom-html-helpers-cs

MVC4 - Partial View Model binding during Submit

I have view model which has another child model to render the partial view (below).
public class ExamResultsFormViewModel
{
public PreliminaryInformationViewModel PreliminaryInformation { get; set; }
public string MemberID { get; set; }
public string MemberName { get; set; }
public int PatientID { get; set; }
public string ConfirmationID { get; set; }
public bool IsEditable { get; set; }
#region Select Lists
public SelectList ProviderOptions { get; set; }
#endregion
}
public class PreliminaryInformationViewModel
{
public string ProviderName { get; set; }
public string ProviderID { get; set; }
public string ServiceLocation { get; set; }
}
This PreliminaryInformationViewModel view model also used as a child models in another view model since this preliminary information can be updated at different pages.
So I created this preliminary information as a separate partial and to include in other pages.
#{Html.RenderPartial("_PreliminaryInformation", Model.PreliminaryInformation);}
Inside the partial
#model Web.Models.Preliminary.PreliminaryInformationViewModel
<div>
#Html.TextBoxFor(x => x.DateOfService })
</div>
But the problem is during submit this preliminary model is always null due to the reason HTML name attribute is always is rendered as
but when I pass the parent model to the partial as below.
#model Web.Models.Exam.ExamResultsFormViewModel
<div>
#Html.TextBoxFor(x => x.PreliminaryInformation.DateOfService })
</div>
Now the HTML element is generated as
<input type = 'text' name='PreliminaryInformation.DateOfService.DateOfService' id='PreliminaryInformation.DateOfService'>
and it binds properly during the submit.
I understand MVC bind the element value based on the name attribute value, but the second implementation would need me to create a multiple partial for each page, which I don't like.
So far I couldn't find a solution to work with the first implementation, is there way I can make preliminary information model value bind during submit with the first implementation.
I know its a bit late but it might help to someone
If you have complex model, you can still pass it into partial using:
#Html.Partial("_YourPartialName", Model.Contact, new ViewDataDictionary()
{
TemplateInfo = new TemplateInfo()
{
HtmlFieldPrefix = "Contact"
}
})
where I have defined model with property "Contact". Now what HtmlFieldPrefix do is add the property binding for each model "so the model binder can find the parent model"
There is a blog post about it: http://www.cpodesign.com/blog/bind-partial-view-model-binding-during-submit/
.NET Core 2 binding
In .NET Core 2 and MVC the answer above will not work, the property is no longer settable.
How ever the solution is very similar.
#{ Html.ViewData.TemplateInfo.HtmlFieldPrefix = "Contact"; }
#await Html.PartialAsync("_YourPartialName", Model.Contact)
after you can submit your model, it will bind again.
Hope that helps
You can add the HtmlFieldPrefix to the top of your partial view:
#{
ViewData.TemplateInfo.HtmlFieldPrefix = "Contact";
}
This is the same approach as that described by #cpoDesign but it means you can keep the prefix in your partial view if you need to do that.
You need to create an editor template for PreliminaryInformationViewModel to replace the partial view, then call with Html.EditorFor( m => m.PreliminaryInformation ). Reference this solution. Creating the template should be as simple as moving your partial view to the Views/Shared/EditorTemplates directory. Html.EditorFor(...) will automatically use this template based on the type you're passing in as the model (in this case, PreliminaryInformationViewModel)
I also ran into this problem. I will explain my solution using your code. I started with this:
#{
Html.RenderPartial("_PreliminaryInformation", Model.PreliminaryInformation);
}
The action corresponding to the http post was looking for the parent model. The http post was submitting the form correctly but there was no reference in the child partial to the parent partial. The submitted values from the child partial were ignored and the corresponding child property remained null.
I created an interface, IPreliminaryInfoCapable, which contained a definition for the child type, like so:
public interface IPreliminaryInfoCapable
{
PreliminaryInformationViewModel PreliminaryInformation { get; set; }
}
I made my parent model implement this interface. My partial view then uses the interface at the top as the model:
#model IPreliminaryInfoCapable
Finally, my parent view can use the following code to pass itself to the child partial:
#{
Html.RenderPartial("ChildPartial", Model);
}
Then the child partial can use the child object, like so:
#model IPreliminaryInfoCapable
...
#Html.LabelFor(m => m.PreliminaryInformation.ProviderName)
etc.
All of this properly fills the parent model upon http post to the corresponding action.
Quick Tip: when calling your EditorFor method, you can set the name of the template as a parameter of the Html.EditorFor method. Alternatively, naming conventions can be your friend; just make sure your editor template filename is exactly the same name as the model property type
i.e. model property type 'CustomerViewModel' => 'CustomerViewModel.cshtml' editor template.
Please make the below changes to your partial page. so it will come with your Parent model
//Parent Page
#{Html.RenderPartial("_PreliminaryInformation", Model.PreliminaryInformation);}
//Partial Page
#model Web.Models.Preliminary.PreliminaryInformationViewModel
#using (Html.BeginCollectionItem("PreliminaryInformation", item.RowId, true))
{
<div>
#Html.TextBoxFor(x => x.DateOfService })
</div>
}
For .net core 2 and mvc, use do like below:
#{
Html.ViewData.TemplateInfo.HtmlFieldPrefix = "Contact";
}
#await Html.PartialAsync("_YourPartialViewName", Model.Contact)

Create ViewModel for Navigation

I have an MVC 4 application with several views. I.e. Products, Recipes, Distrubutors & Stores.
Each view is based around a model.
Let's keep it simple and say that all my controllers pass a similar view-model that looks something like my Product action:
public ActionResult Index()
{
return View(db.Ingredients.ToList());
}
Ok so this is fine, no problems. But now that all of my pages work I want to change my navigation (which has dropdowns for each view) to load the items in that model.
So I would have a navigation with 4 Buttons (Products, Recipes, Distrubutors & Stores).
When you roll over each button (let's say we roll over the products button) then a dropdown would have the Products listed.
To do this I need to create some type of ViewModel that has all 4 of those models combined. Obviously I can't just cut out a PartialView for each navigation element and use
#model IEnumerable<GranSabanaUS.Models.Products>
And repeat out the Products for that dropdown, because then that navigation would only work in the Product View and nowhere else.
(After the solution)
AND YES ROWAN You are correct in the type of nav I am creating, see here:
Introduction
I'm going to be making a few assumptions because I don't have all the information.
I suspect you want to create something like this:
Separating views
When you run into the issue of "How do I put everything into a single controller/viewmodel" it's possible that it's doing too much and needs to be divided up.
Don't treat your a final page as one big view - divide the views up into smaller views so they are doing 'one thing'.
For example, the navigation is just one part of your layout. You could go even further to say that each dropdown menu is a single view that are part of the navigation, and so on.
Navigation overview
Suppose you have a _Layout.cshtml that looks like this:
<body>
<div class="navbar">
<ul class="nav">
<li>Products</li>
<li>Recipes</li>
</ul>
</div>
#RenderBody()
</body>
As you can see we have a simple navigation system and then the main body is rendered. The problem that we face is: How do we extract this navigation out and give it the models it needs to render everything?
Extracting the navigation
Let's extract the navigation into it's own view. Grab the navigation HTML and paste it into a new view called __Navigation.cshtml_ and put it under ~/Views/Partials.
_Navigation.cshtml
<div class="navbar">
<ul class="nav">
<li>Products</li>
<li>Recipes</li>
</ul>
</div>
Create a new controller called PartialsController. Create a new action to call our navigation.
PartialsController.cs
[ChildActionOnly]
public class PartialsController : Controller
{
public ActionResult Navigation()
{
return PartialView("_Navigation");
}
}
Update our Layout to call the navigation.
_Layout.cshtml
<body>
#Html.Action("Navigation", "Partials")
#RenderBody()
</body>
Now our navigation is separated out into its own partial view. It's more independent and modular and now it's much easier to give it model data to work with.
Injecting model data
Suppose we have a few models such as the ones you mentioned.
public class Product { //... }
public class Recipe { //... }
Let's create a view-model:
NavigationViewModel.cs
public class NavigationViewModel
{
public IEnumerable<Product> Products { get; set; }
public IEnumerable<Recipe> Recipes { get; set; }
}
Let's fix up our action:
PartialsController.cs
public ActionResult Navigation()
{
NavigationViewModel viewModel;
viewModel = new NavigationViewModel();
viewModel.Products = db.Products;
viewModel.Recipes = db.Recipes;
return PartialView("_Navigation", viewModel);
}
Finally, update our view:
_Navigation.cshtml
#model NavigationViewModel
<div class="navbar">
<ul class="nav">
#foreach (Product product in Model.Products)
{
#<li>product.Name</li>
}
#foreach (Recipe recipe in Model.Recipes)
{
#<li>recipe.Name</li>
}
</ul>
</div>
public class MenuContents
{
public IEnumerable<Products> AllProducts { get; set; }
public IEnumerable<Recepies> AllRecepies { get; set; }
public IEnumerable<Distributors> AllDistributors { get; set; }
public IEnumerable<Stores> AllStores { get; set; }
private XXXDb db = new XXXUSDb();
public void PopulateModel()
{
AllProducts = db.Products.ToList();
AllRecepies = db.Recepies.ToList();
AllDistributors = db.Distributors.ToList();
AllStores = db.Stores.ToList();
}
}
Then in your controller
public ActionResult PartialWhatever()
{
MenuContents model = new MenuContents();
model.PopulateModel();
return PartialView("PartialViewName", model);
}
Then in your partial view
#Model MenuContents
... do whatever here