identifier expected error on controller - asp.net-mvc

From following controller i am getting error- identifier expected. Please have a look on the screen shot for better understanding. Picture attached
Controller:
[ChildActionOnly]
public PartialViewResult _GuestNav()
{
using (var db = new TestWebDbEntities())
{
var categories = db.Categories.(x=>x.SubCategories).ToList();
return PartialView("_GuestNav", categories);
}
}

A simple Select LINQ method can populate Categories data set into IEnumerable object you want to pass into view with ToList() method:
[ChildActionOnly]
public PartialViewResult _GuestNav()
{
using (var db = new TestWebDbEntities())
{
var categories = db.Categories.Select(x => x.SubCategories).ToList();
return PartialView("_GuestNav", categories);
}
}

Related

Returning more than just one model to the View?

I am fairly new to MVC, and I've been reading a bit about ViewModels, but how do I go about sending two models to my View, where the queries are like so
public ActionResult Index(int Id)
{
var People = from a in db.Person
select a;
var Data = from a in db.Member
where a.Person.PersonId.Equals(Id)
select new
{
a.Project.ProjectId,
a.Project.Name,
a.Project.Customer,
a.Project.TechProfile.Select(x => new
{
x.TechId,
x.Name,
x.Elements
}),
a.MemberId,
a.Role,
a.Start,
a.End
};
return View(People);
}
I was using #model IQueryable<GeoCV.Models.Person> before so I could use a #foreach in my View but I don't know how to get my other query to the View so I can get data from it too.
Update
And I'm making a custom class for my Data query, but I don't know how to set the property of TechProfile
Right now I have
public IEnumerable<TechProfile> ProjectTechProfile { get; set; }
In my custom class, but it doesn't work, so I guess I have to specify TechId, Name and Elements?
But how?
A ViewModel wraps around the 2 models you are getting with your 2 queries, so you can return it as a single object to your view. In your case we need to adress another issue first. You are returning an anonymous object in your data query.
This means, your data query needs to return a strongly typed object instead of an anonymous object.
Create a class for your data query:
public class MyCustomDataObject
{
public int ProjectId { get; set; }
//... map all properties as needed
}
then edit your data query to return this object:
var Data = from a in db.Member
where a.Person.PersonId.Equals(Id)
select new MyCustomDataObject
{
ProjectId = a.Project.ProjectId,
//assign all properties
};
Now you need to create the actual ViewModel class:
public class MyViewModel
{
public IEnumerable<Person> Persons { get; set; }
public IEnumerable<MyCustomDataObject> Data { get; set; }
}
And after this you just need to assign the values to it in your Actionmethod:
public ActionResult Index(int Id)
{
var People = from a in db.Person
select a;
var Data = from a in db.Member
where a.Person.PersonId.Equals(Id)
select new MyCustomDataObject
{
ProjectId = a.Project.ProjectId,
//...
};
//store data of both queries in your ViewModel class here:
var vm = new MyCustomDataObject();
vm.Persons = People;
vm.Data = Data
//return ViewModel to View.
return View(vm);
}
And then declare it in your view: #model Namespace.Subfolder.MyCustomDataObject
You can use #Html.Action("actionName","controllerName") method in view. You can divide your original view into multiple partial view and then you can render that partial view with dynamic model binding using #Html.Action("actionName","controllerName") method.
For more details with sample code http://devproconnections.com/development/how-use-aspnet-mvc-render-action-helpers
You can have methods like below to get multiple model in single view
private IList<People> GetPeople()
{
return from a in db.Person
select a;
}
private IList<Data> GetData()
{
return from a in db.Member
where a.Person.PersonId.Equals(Id)
select new
{
a.Project.ProjectId,
a.Project.Name,
a.Project.Customer,
a.Project.TechProfile.Select(x => new
{
x.TechId,
x.Name,
x.Elements
}),
a.MemberId,
a.Role,
a.Start,
a.End
};
}
public ActionResult Index(int Id)
{
var MultipleModel = new Tuple<IList<People>,IList<Data>>(GetPeople(),GetData()) { };
return View(MultipleModel);
}
Here's a codeproject tutorial on the subject.

Display List in View in MVC

I have a List with has three values.I want to display in view.Here is my approach
My Controller Function
public List<Movie> Index()
{
Movie obj = new Movie();
return obj.ShowData();
}
My model class & Function
Database db = DatabaseFactory.CreateDatabase("MyDBLINK");
public int ID { get; set; }
public string Title { get; set; }
public List<Movie> GetData()
{
try
{
DbCommand dbCommand = db.GetStoredProcCommand("SP");
DataSet dsResult = db.ExecuteDataSet(dbCommand);
List<Movie> Prop = new System.Collections.Generic.List<Movie>();
Prop = (from DataRow row in dsResult.Tables[0].Rows
select new Movie
{
ID = Convert.ToInt32(row["ID"].ToString()),
Title = row["Title"].ToString()
}).ToList();
return Prop;
}
catch (Exception ex)
{
return null;
}
}
Here is my view
#model System.Collections.Generic.List<MvcFirst.Controllers.MoviesController>
#foreach (var item in Model)
{
<ul>
<li>#item.ID</li>
<li>#item.Title</li>
</ul>
}
My Question is how to display this list in View?
Secondly Is this approach is Good for CPU?
Everything looks almost fine, your controller should be something like this:
public ActionResult Index()
{
var movie = new Movie();
var result = movie.GetData(); // instance object and read the method to get the list
return View(result);
}
An ActionResult could be any type of result, a View, a File to download, a Javascript, A StyleSheet, etc... but normaly is a View with the same name of action. If your action method is called Index, asp.net mvc will search for a View called Index on the Views folder. The part return View(result); means you are returning this View and passing the result object as a Model to your View.
Your View should be strogly typed with the entity (because you are returning it from the controller), not the controller:
#model System.Collections.Generic.List<Movie>
#foreach (var item in Model)
{
<ul>
<li>#item.ID</li>
<li>#item.Title</li>
</ul>
}
I think you've missunderstood how Controllers and Views work. Your Index() method need to return an ActionResult which will generate your view and return it to the user.
//My Controller Function
public ActionResult Index()
{
Movie obj = new Movie();
return View(obj.GetData()); //This will take the view with the same name as your method (Index in this case) and return it to the client/browser.
}
I hope I understood you question correctly.
Edit: I forgot to make the view stronly typed as Felipe Oriani has showned you

foreach loop in mvc razor to iterate each element from the model and display

I want to Display each element on Razor view from Model through foreach loop,I have no code in Controller
when I run the Application , I get the Error:
Object reference not set to Instance of an Object
Please some body help me, I wrote the code in the View
#model IEnumerable<Models.Web.Category>
#foreach(var item in Model){
#item.CategoryName
}
and My Controller is
public ActionResult Category(){
return View();
}
I mean something like this:
public ActionResult Category(){
var categories = db.Categories;
return View(categories);
}
OR
public ActionResult Category(){
List<Category> categories = new List<Category>();
categories.Add(new Category() { ID = 1, Name = "Bikes" });
categories.Add(new Category() { ID = 2, Name = "Cars" });
categories.Add(new Category() { ID = 3, Name = "Trucks" });
return View(categories);
}
You should initialize your model in controller...
Model is null.
If you want to display data from the model, you need to pass a model from the controller.
Look your view is expecing a Model:
#model IEnumerable<Models.Web.Category>
In your Controller you're not passing anything to the view, so the view has null as a Model.
You need to create your collection IEnumerable<Category> and pass it to the view.

Model error and re-retrieving combo-box items

On loading up a form, I retrieve a list of items to put in a combo-box. Now lets say during the post, there is an error. I have to re-write the code to get and build back my viewmodel again?
For eg.
public ActionResult Index()
{
var vModel = GetViewModel();
return View(vModel);
}
[HttpPost]
public ActionResult Index(SomeModel model)
{
if (ModelState.IsValid)
{
}
else
{
//Why do I have to write monkey-code here?
var vModel = GetViewModel();
return View(vModel);
}
}
Am I going to have to do it like this example where I have a method to build my viewmodel for both actions?
Why not just return Index(); instead?

The model item passed into the dictionary is of type 'System.Data.Objects.ObjectQuery`1

im trying to get the controller in my mvc application to edit a specific entity from a data model once the user clicks on the edit button, however I can't seem to make it work. I keep getting this error
The model item passed into the dictionary is of type 'System.Data.Objects.ObjectQuery`1[MvcApplication1.Models.New]' but this dictionary requires a model item of type 'MvcApplication1.Models.New'.
what am I doin wrong. is it due to the strongly typed view??
here is my controller:
public ActionResult Edit(int id)
{
var productToEdit = from s in _entities.NewSet // return the story matching the clicked id
where s.storyId == id
select s;
return View(productToEdit);
}
// POST : Edit
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(New productToEdit)
{
try
{
var originalNews = (from s in _entities.NewSet
where s.storyId == productToEdit.storyId
select s).FirstOrDefault();
_entities.ApplyPropertyChanges(originalNews.EntityKey.EntitySetName, productToEdit);
_entities.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
can someone give me a few pointers please. Im still new to all of this.
Change your Edit action with Int Parameter to as follows:
public ActionResult Edit(int id)
{
var productToEdit = from s in _entities.NewSet
where s.storyId == id
select s;
return View(productToEdit.FirstOrDefault());
}

Resources