I have a model for a view. This view contains a an #Html.DropDownList whose values are in a model. How can I have my view take both model for different parts of the program?
For example, I have
#model IEnumerable<projectname.mymodel>
#{
ViewBag.Title = "my title"
}
<!--This should use a different model-->
<p>#Html.DropDownList(m =>m.name), new set(Model.list, "value", "key"))
If I have model1 and model2(connects to database)-all stored in the Model folder; and a big model class as something like
public class MyViewModel {
public model1 var1 { get; set; }
public IEnumerable<projectname.Model.model2> var2 { get; set; }
}
And i call this model in my view:
#model ProjectName.Models.Models
How do I reference an item in model1 or model2?
Just pass a new class as model to your view which contains all the data you need:
public class MyViewModel {
public SelectList list { get; set; }
public IEnumerable<projectname.mymodel> Items { get; set; }
}
Another approach would be to pass the list in the Viewbag:
Viewbag.list = new SelectList() ...
Related
In asp.net core MVC I need to show two tables in a single view. I have one page and there is a submit button on click of that it will go to another view .there in need to show two tables. I want to use JSON. but from the controller, it returns view model .so how to convert view model data in JSON format to show it in an HTML table?
you can use the Viewbag into your controller to show two tables in one view.
keep this at the top of your view page
#using Newtonsoft.Json
And I think then you can do this which you want.
#Html.Raw(#JsonConvert.SerializeObject(ViewBag.something))
I don't know why you want to return json, the usual solution is to create a ViewModel.
public class Model1
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Model2
{
public int Id { get; set; }
public string Name { get; set; }
}
public class ViewModel
{
public Model1 Model1 { get; set; }
public Model2 Model2 { get; set; }
}
Then you can return a ViewModel to the view.
If you need to return Json,please provide your class model and your view code.
I am working on creating a datagrid in ASP MVC 3 where I have two tables in one view. Each table is being used from its own Model. Therefore, I would have to call two Models into one View which does not seem as simple as I wish it was.
I am pretty new to MVC and I was looking through Stack and found this link:
Two models in one view in ASP MVC 3
Which seems to be the direction that i would want to go... I think.
Here is the code for my first model:
[Table]
public class Model1
{
[Column(IsPrimaryKey = true, IsDbGenerated = true)]
public int Column1 { get; set; }
[Column]
public string Column2 { get; set; }
[Column]
public string Column3 { get; set; }
}
Here is the code for my second model:
[Table]
public class Model2
{
[Column(IsPrimaryKey = true, IsDbGenerated = true)]
public int Column1 { get; set; }
[Column]
public int Column2 { get; set; }
[Column]
public string Column3 { get; set; }
[Column]
public string Column4 { get; set; }
}
Here is the code for the Parent View Model that the other Stack Forum suggested:
public class ParentModelView
{
public Model1 Model1 { get; set; }
public Model2 Model2 { get; set; }
}
I was able to get each one to work individually so i know that it isn't any other issue. The other Stack Forum seemed to be a little too vague for my understanding. I feel like there would have to be more to it than just adding another parent model that is using each model within it (what i am getting out of it).
Some other information that you may find useful is that each model is in its own file. Also, Here is my error:
The model item passed into the dictionary is of type
'System.Data.Linq.Table 1[Model1]', but this dictionary requires a model
item of type 'System.Collections.Generic.IEnumerable 1[ParentModelView]'.
Description: An unhandled exception occurred during the execution of the
current web request. Please review the stack trace for more information
about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The model item passed
into the dictionary is of type 'System.Data.Linq.Table 1[Model1]', but this
dictionary requires a model item of type
'System.Collections.Generic.IEnumerable 1[ParentModelView]'.
Source Error:
An unhandled exception was generated during the execution of the current
web request. Information regarding the origin and location of the exception
can be identified using the exception stack trace below.
---EDIT 1---
Here is the code inside of my View:
#model IEnumerable<ParentModelView>
#{
WebGrid gridModel1 = new WebGrid(Model);
WebGrid gridModel2 = new WebGrid(Model);
}
<div class="Table">
<h2>Model1</h2>
#gridModel1.GetHtml(columns: new[] {
gridModel1.Column("Column1"),
gridModel1.Column("Column2"),
gridModel1.Column("Column3")
})
</div>
<div class="Table" id="rightTable">
<h2>Model2</h2>
#*#gridModel2.GetHtml(columns: new[] {
gridModel2.Column("Column1"),
gridModel2.Column("Column2"),
gridModel2.Column("Column3"),
gridModel1.Column("Column4")
})*#
</div>
EDIT 2
As most of you have requested, here is my controller code. I know that it is not right because i am not quite sure how to pass through the information between two models into the same view. If someone would be able to help with that, it would be much appreciated.
public class HomeController : Controller
{
public ActionResult Index()
{
Model1Repo repoModel1 = new Model1Repo ();
var Model1RepoSQL = repoModel1.All();
Model2Repo repoModel2 = new Model2Repo();
var Model2RepoSQL = repoModel2.All();
return View(Model1RepoSQL);
}
}
Any other information would be much appreciated. Thanks!
I think what you want is something more like this:
public class ParentModelView
{
public IEnumerable<Model1> Model1 { get; set; }
public IEnumerable<Model2> Model2 { get; set; }
}
And in your view
#model ParentModelView
#{
WebGrid gridModel1 = new WebGrid(Model.Model1);
WebGrid gridModel2 = new WebGrid(Model.Model2);
}
EDIT;
Apparently, you aren't populating the parent model correctly. I assumed you would understand how to do that.
public ActionResult MyAction() {
var model1 = // get rows of model1
var model2 = // get rows of model2
return View("myview", new ParentModelView { Model1 = model1, Model2 = model2 }) ;
}
You can always use ViewModel in this case. For example create a viewmodel
public class ViewModel{
public int Table1Column1 { get; set; }
public string Table1Column2 { get; set; }
public string Table1Column3 { get; set; }
public int Table2Column1 { get; set; }
public int Table2Column2 { get; set; }
public string Table2Column3 { get; set; }
public string Table2Column4 { get; set; }
}
Get the data into ViewModel from both the models in business layer or data access layer.
P.S: What McGarnagle said is true but it's vice versa, you are sending child models into the view while it is expecting ParentModelView. If you can post parts of code for controller and view, it would be helpful.
I Want to display label for input box but I have 3 different class which contains information
Like Class1 [Settings] is like this
public class Settings
{
public static decimal Setting1 { get; set; }
public static decimal Setting2 { get; set; }
}
we are populating data in above class at the time of login, so we kept it in session
My Class2 [AppConst] is like this
public static class AppConst
{
public const string _unitPersentage = "%";
public const string _unitPerMT = "Per MT";
}
and my Modal is like this
public class Sale
{
[Display(Name = "Discount")]
public double DiscountAmount { get; set; }
[Display(Name = "Road Tax")]
public double RoadTaxAmount { get; set; }
}
Now in my View for Model "Sale" I want to display label for property "DiscountAmount" like this
Discount 5% (Lable of DiscountAmount + Value of Settings.Setting1 + value of AppConst._unitPersentage)
Here I can get label for "DiscountAmount" by using
#Html.TextBoxFor(o => o.DiscountAmount)
but how can I display value of tow other members "Settings.Setting1" & "AppConst._unitPersentage"
You can flatten out your model and then use an editor template to show that complex label.
The Flatten Model
public class CustomModel
{
[Display(Name = "Discount")]
public double DiscountAmount { get; set; }
[Display(Name = "Road Tax")]
public double RoadTaxAmount { get; set; }
public decimal Setting1 { get; set; }
public string UnitPercent {get;set;}
}
The Template
The template should be placed inside the EditorTemplates folder under the Shared folder.
#model CustomModel
#{
var inputProp = ViewData.ModelMetadata.Properties
.First(o => o.PropertyName == "DiscountAmount");
}
<label for="#inputProp.PropertyName" id="#(inputProp.PropertyName+"Label")">
Discount 5% (#inputProp.ShortDisplayName #Model.Setting1#Model.UnitPercent)
<input id="#inputProp.PropertyName" type="text"
name="#inputProp.PropertyName" />
</label>
Controller Code
This is how you will create and pass the model to your view:
return View(new CustomModel
{
// get it from your datastore or where ever the source may be
Setting1 = getFromDbOrSomewhere(),
UnitPercent = AppConst._unitPersentage,
});
Your View
Then consume it on your view like this
#model CustomModel
#Html.EditorFor(m => Model)
The beauty of this approach is that you can always discard the template and do inline html in your view. Also, the logic of having an "input + label" for your model is separated into one place.
You have few alternatives to try. If the data is only for display purpose you may use - ViewData or ViewBag or TempData to pass the values for Settings and AppConst, whatever suits your purpose. See here.
In this case, if these are static objects, you may refer them in the view as:
<Namespace>.Settings.Setting1 or <Namespace>.AppConst._unitPerMT.
Please take this as a starting point and follow proper best practices for development. Please do not declare public members with underscore. Underscores are generally prefixed to private members.
I have created MVC3 application using Entity Framework Code First method. My model is very simple:
public class Employee
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int YearsAtCompany { get; set; }
}
and context class is
public class EmployeeDB : DbContext
{
public DbSet<Employee> Employees { get; set; }
}
and controller looks like this:
EmployeeDB context = new EmployeeDB();
public ActionResult Index()
{
return View(context.Employees);
}
}
I have created EmployeesDb.mdf and Employee table.
but I get this error:
The model item passed into the dictionary is of type 'System.Data.Entity.DbSet`1[DFEmployees.Models.Employee]', but this dictionary requires a model item of type 'DFEmployees.Models.Employee'.
[Updated]
#model DFEmployees.Models.Employee
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
Please suggest solution.
It's looks like your view are waiting for a single employee, and you are triying to fill the view with a DBSet of employees.
To solve it, you can set the #model of the view to an IEnumerable of employees, or send only one employee to the view, depending of what are you showing in the view.
EDIT: I think this problem is not related with the previous one. Check this link, I hope it helps you: LINK
Your controller action returns a list of employees so adapt your model respectively in the view:
#model IEnumerable<DFEmployees.Models.Employee>
Or if you wanted to use a single employee make sure you pass a single employee to the view:
public ActionResult Index()
{
return View(context.Employees.FirstOrDefault());
}
and then you can have:
#model DFEmployees.Models.Employee
I have this model:
namespace easyBooking.Models
{
public class CardInfo
{
public string name { get; set; }
public string adress { get; set; }
public string zipcode { get; set; }
public string city { get; set; }
public string ccsID { get; set; }
public string birthday { get; set; }
public string nationalitet { get; set; }
public string cardType { get; set; }
}
}
which I populate from a function and return to the controller. The problem is that I cannot hand this model to my view, since it does not implement IEnumerable... Instead I have to add information to the viewBag like this:
var cardInfo = FunctionLib.cardCampingPas(myArray);
ViewData.Add("name", cardInfo.name);
ViewData.Add("adress", cardInfo.adress);
ViewData.Add("nationalitet", cardInfo.nationalitet);
ViewData.Add("ccsID", cardInfo.ccsID);
ViewData.Add("zipcode", cardInfo.zipcode);
ViewData.Add("city", cardInfo.city);
ViewData.Add("cardType", cardInfo.cardType);
return View("../Reservation/New", ViewData);
which is kind of stupid, when I should be able to just add the cardInfo model directly to the View.
var cardInfo = FunctionLib.cardCampingPas(myArray);
return View("../Reservation/New", cardInfo);
So basically I just need to pass a bunch of strings to the view. How can my model CardInfo be accessed directly from my view?
Update
#rene - view data where I added a #model declaration. I did get some errors when I tried it last, but it must have been because I tried to foreach it or something.. now... just no error, and I have no idea if anything is passed to the view or how to get the data.
#model easyBooking.Models.CardInfo
#{
ViewBag.Title = "New";
}
<h2>Ny reservation</h2>
<p>Benyttet kort: #Model.cardType</p>
This now works...
You can pass your collection directly to the view.
In the view, you'll need to declare the model type:
#model IEnumerable<CardInfo>