Partialview and passing data to layout MVC3 - asp.net

i want to show categories to all pages by using layout and here my way:
here my model (NewsCategoriesModel)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace GiaoXuKeSat.Models
{
public class NewsCategoriesModel
{
public int NewsCategoriesID { get; set; }
public string NewsCategoriesName { get; set; }
}
}
Here Partialview (_NewsCategories)
#using System.Linq;
#using System.Linq;
#model IEnumerable<GiaoXuKeSat.Models.dms_NewsCategory>
#foreach (var item in Model) {
<ul id="dmsMenuULUL">
<li>#item.NewsCategoriesName</li>
</ul>
}
and i print that partialview to layout
#Html.Partial("_NewsCategories");
but i got Object reference not set to an instance of an object.
at
#foreach (var item in Model) {

You need to pass the model that your partial view needs to it. Such as.
#Html.Partial("_NewsCategories", Model.NewsItems);
If you leave the model out, you are simply passing the current view model to your partial. You can also use the ViewBag.
If you are calling a Partial from the master/layout page it is unlikely you'll have your model available on every single page. So in this case, it is better to create a controller/action that returns your news item model to a partial view and then call with...
#Html.Action("NewsCategories", "NewsController");
Which will then run the specified action and display the partial view that the action calls.

Related

Unable to access data annotation from partial class

Using ASP.NET MVC pattern I have an Entity Framework stored in the Models->Northwind which includes Region.cs class. I also have a Partial Folder which contains RegionalPartial.cs which includes Data annotation for region.cs
Here is the Directory structure
The Region.cs looks like :
namespace Map.Models.Northwind
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class Region
{
public int RegionID { get; set; }
public string RegionDescription { get; set; }
}
}
and the RegionPartial.cs is like
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Map.Models.Northwind.Partials
{
using System.ComponentModel.DataAnnotations;
[MetadataType(typeof(RegionMetaData))]
public partial class Region {}
public class RegionMetaData
{
[Required]
[Display(Name = "REGION DESCRIPTION")]
public object RegionDescription { get; set; }
}
}
but the Region.cs is not using the data annotation stored in the RegionPartial.cs! Why is this happening and how I can fix this?
Change the namespace in RegionPartial.cs from
Map.Models.Northwind.Partials
to
Map.Models.Northwind

EF Code First EntityType has no key defined even if Annotation is added

Trying to do Migrations but after executing add-migration command,
it says that:
EntityType 'City' has no key defined. Define the key for this EntityType.
THis is my model:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace CodeFirstPrimer.Models.NHL
{
public class City
{
[Key]
public int CityId;
public String CityName;
public int Population;
}
}
I had already put an annotation on CityId.
Anyone has hint where/what could possibly is wrong?

how to build a dropdownlistfor in asp mvc4 from a db inside a partial view

while ive build mvc projects i havent done them in asp.net mvc4.5
so pls forgive me if this question seems really obvious to answer
or if im making obvious noob mistakes
pls feel free to correct all issues...
ive actually been googling all weekend and i seem to get bits of answers
but havent been able to pull it all together
so as the title says im trying to build a simple dropdownlistfor
where the data is pulled from the db
to add another layer of complexity
this DDLF is in a partial view
so heres what ive got
model:
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace proj.Models
{
public class chartType
{
public int id { get; set; }
[Required]
public string typename { get; set; }
}
public class chartTypeVM
{
[Display(Name = "selectedID")]
public int selectedChartType { get; set; }
public IEnumerable<SelectListItem> List { get; set; }
}
}
controller:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using proj.Models;
namespace proj.Controllers
{
public class HomeController : Controller
{
orojDB db = new orojDB ();
public ActionResult Index()
{
chartTypeVM model = initialiseSM();
return View(model);
}
private chartTypeVM initialiseSM()
{
// make scenario DDL
// using chartTypes for now
var q = db.chartTypes
.Select(ct=> new {
ct.id,
ct.typename
})
.AsEnumerable()
.Select(ct => new SelectListItem {
Value = ct.id.ToString(),
Text = ct.typename
});
var cts = new chartTypeVM{
List = q.AsEnumerable()
};
cts.selectedChartType = 1;
Debug.WriteLine("asdfasdf");
return cts;
}
}
}
view:
#using proj.Models
#model chartTypeVM
<h3>We suggest the following:</h3>
#* *************** sections *************** *#
#section sm {
<div id="sm">
<section class="content-wrapper sm-content">
#Html.Partial("_smPartial", Model)
</section>
<div class="smCloseD"><img src="/Images/closeArrow.png" alt="Open Scenario Manager" /></div>
<div class="clear"></div>
</div>
}
main layout (most of it not shown) :
#using proj.Models
#model chartTypeVM
<section class="content-wrapper main-content">
#RenderBody()
</section>
#RenderSection("sm",false);
and finally the partial:
#using proj.Models
#model chartTypeVM
<section class="smVars">
<div class="varLabel">Scenario:</div>
<div class="varInput">#Html.DropDownListFor( model=>model.selectedChartType, (SelectList)model.List)</div>
</section>
with the things ive tried
i getting errs like:
- The name 'model' does not exist in the current context
- or the one about not being able to use dynamic variables
- or something being inferred
anyways if you could help id be very grateful
=:-)
thanks!
In order to use DropDownListFor helper your view needs to be strongly typed to a model. In your case that would be the chartTypeVM class. So add a #model directive to the top of your partial view indicating the view model being used:
#model chartTypeVM
<section class="smVars">
<div class="varLabel">Scenario:</div>
<div class="varInput">
#Html.DropDownListFor(model => model.selectedChartType, (SelectList)Model.List)
</div>
</section>

Server Side Scripting not working

I am new to MVC and creating a sample application by viewing this video.I have created a class in Model and a controller.Now when i try to access Class property through view,i am not able to access it,even when i am writing in view like <%=Model.Id %>,the angular brackets are not yellow marked as in case of server side scripting.I am not able to find where the problem is?
Class Customer in Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcCustomer.Models
{
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public double Amount { get; set; }
}
}
and Controller is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcCustomer.Models;
namespace MvcCustomer.Controllers
{
public class LoadCustomerAndDisplayController : Controller
{
//
// GET: /LoadCustomerAndDisplay/
public ActionResult Index()
{
Customer customer = new Customer();
customer.Name = "Devesh";
customer.Amount = 22.9;
customer.Id = 1;
return View(customer);
}
}
}
and my strongly typed view(IntelliSense is also not working) is
#model MvcCustomer.Models.Customer
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<div>
The Customer id is: <%= Model.Id %>
</div>
</body>
</html>
First off, you're using a Razor view, not an ASP.NET view, so the syntax is #Model.Id not <%= Model.Id %>.
Your view is coded with Razor.
To initiate server side behavior use #, not <%= ... %>
Have a look here.
http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx

Modify Model structure without changing existing EF 4.x Generated Model in Database First Approach

I'm using ASP.NET MVC 3.0 Database First approach with EF 4.x. Models are generated with EF 4.x DBContext Generator. Now I want to change model structure but don't want to change existing model because if database is modified I have to generate model again so the changes will be gone. I think it should be done by overriding partial classes but not clear. Is there any example to do it? what is the best way to implement it?
Edit: I have to add some additional validations in some Models, not all. I want to create independent models which overrides the generated classes and in case if EF models are regenerated there is no harm on our customized models.
you can change the *.tt file for generating objects from model. What do you want to change objects.
You can create partial classes like this
namespace MyProject.Data{
public partial class User{}
}
but your partial class should be the same namespace of EF created classes
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
[MetadataType(typeof(UserMetadata))]
public partial class User : IEntity
{
internal class UserMetadata
{
[DisplayName("User Name")]
public virtual string UserName
{
get;
set;
}
[DisplayName("First Name")]
public virtual string FirstName
{
get;
set;
}
[DisplayName("LastName")]
public virtual string LastName
{
get;
set;
}
}
}

Resources