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
Related
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);
}
}
I have two models and I need to display data in my layout page and in every page that the user visit. Those two models have not any relationship between them so I don't need any join.
this is my controller
public ActionResult Index()
{
var notification = (from n in db.Notification
where n.NotificationIsSeen == true
select n);
var task = (from t in db.Task
where t.TaskIsSeen == true
select t);
return View();// I not sure how to return both of queries
}
I also create a model that contains both of them but I 'not sure if this is the right way
public class Layout
{
public Notification Notification { get; set; }
public Task Task { get; set; }
}
and in my layout page
#model IEnumerable<MyprojectName.Models.Layout>
//other code
#foreach (var item in Model)
{
<li>#Html.DisplayFor(modelItem => item.Notification.NotificationSubject ) </li>}
//other code
#foreach (var item in Model)
{
<li>#Html.DisplayFor(modelItem => item.Task.TaskSubject )
</li>
}
I have seen other similar question but they work with join tables.
I need some help on returning data of both tables. thank you in advance
Your queries in your action method both return collections of data. To accommodate this your view model needs to have two lists and needs to look something like this. You have to be able to store these collections in lists when sending them to the view:
public class Layout
{
public IEnumerable<Notification> Notifications { get; set; }
public IEnumerable<Task> Tasks { get; set; }
}
To populate these lists change the code in your action method to this. Create an instance of Layout, populate the two lists and then send the instance to the view:
public ActionResult Index()
{
Layout model = new Layout();
model.Notifications = (from n in db.Notification
where n.NotificationIsSeen == true
select n);
model.Tasks = (from t in db.Task
where t.TaskIsSeen == true
select t);
return View(model);
}
Your view needs to accept and instance of Layout:
#model MyprojectName.Models.Layout
#foreach (var notification in Model.Notifications)
{
<div>
#notification.NotificationSubject
</div>
}
#foreach (var task in Model.Tasks)
{
<div>
#task.TaskSubject
</div>
}
I hope this helps.
Please declare list type of model in you layout model
Layout Model
public class Layout
{
public IEnumerable<Notification> Notifications { get; set; }
public IEnumerable<Task> Tasks { get; set; }
}
Controller
public ActionResult Index()
{
Layout model = new Layout();
model.Notifications = (from n in db.Notification
where n.NotificationIsSeen == true
select n);
model.Tasks = (from t in db.Task
where t.TaskIsSeen == true
select t);
return View(model);
}
View
#model MyprojectName.Models.Layout
#foreach(var item in Model.Notifications)
{
// access your item.propertyname
}
#foreach(var item in Model.Task)
{
// access your item.propertyname
}
Using partial view for build the dynamic header
1 - create action with partial view and display data
2 - go to layout to call this
#Html.partial("Action","Controller")
i have two Html links
and
When i click First Link it goes to Sample controller and goes to advetisement Methode and returns View
public ActionResult advetisement{
// here iam reciveing data to variable
return view()
} now it retuns to view and data is binded and displays Page.Now when i click second link it should go to Same controller(advetisement) and return same Data but view should be diffrent since html styling is changed.
You can load two different views from the same controller action:
if (model.SomeCondition == true)
{
return View("ViewName1", model);
}
return View("ViewName2", model);
Then use your view model to store the condition which determines which view to display:
public class MyViewModel
{
public bool SomeCondition { get; set;}
public object Data { get; set; }
}
I think the easiest way is just having two actions with different names. Of course, code duplication should be extracted to the separate method. Something like this:
public ActionResult Advertisement()
{
return AdvertisementInternal("Advertisement");
}
public ActionResult Advertisement1()
{
return AdvertisementInternal("Advertisement1");
}
private ActionResult AdvertisementInternal(string viewName)
{
// filling ViewBag with your data or creating your view model
...
return View(viewName);
}
But if an appropriate way is the only action for both views then you should have a flag to distinguish the views. It can be added to URL. Something like this:
// on the view
#Html.ActionLink("Link1", "Advertisement", "Sample", new { Id = "View1" }, null)
#Html.ActionLink("Link2", "Advertisement", "Sample", new { Id = "View2" }, null)
// in the controller
public ActionResult Advertisement(string id)
{
if (id == "View1" || id == "View2")
{
// filling ViewBag with your data or creating your view model
...
return View(id);
}
return HttpNotFound();
}
public ActionResult About()
{
var roles = System.Web.Security.Roles.GetAllRoles();
return View();
}
I don't know how to take this string on view page. Please help me.
You should have your view accept a string[] Model and pass this model from your controller to your view like this:
public ActionResult About()
{
var model = System.Web.Security.Roles.GetAllRoles();
return View(model);
}
In your view you'd have something like this (assuming you are using the Razor ViewEngine):
#model string[]
<ul>
#foreach(var role in model)
{
<li>#role</li>
}
</ul>
The View method takes a model which can be your string[].
public ActionResult About()
{
var roles = System.Web.Security.Roles.GetAllRoles();
return View(roles);
}
Then your view would look something like this
#model System.Array
#foreach (var role in Model)
{
...
}
You can set a ViewBag
public ActionResult About()
{
ViewBag.roles = System.Web.Security.Roles.GetAllRoles();
return View();
}
and u can access this ViewBag object on the page by #ViewBag.roles
To display the list
foreach(var customrole in ViewBag.roles)
{
#customrole.Roles // This might be some property you need to display
}
I am learning MVC4. I could display records in a tabular format using foreach.
Now, I need to display theDescription of (only) first Topic object in a label. I need to do it without a foreach. How can we do it?
VIEW
#model MvcSampleApplication.Models.LabelDisplay
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm())
{
foreach (var item in Model.Topics.Select((model, index) => new { index, model }))
{
<div>#(item.index) --- #item.model.Description---- #item.model.Code</div> <div></div>
}
}
Controller Action
public ActionResult Index()
{
LabelDisplay model = new LabelDisplay();
Topic t = new Topic();
t.Description = "Computer";
t.Code=101;
Topic t3 = new Topic();
t3.Description = "Electrical";
t3.Code = 102;
model.Topics = new List<Topic>();
model.Topics.Add(t);
model.Topics.Add(t3);
return View(model);
}
Model
namespace MvcSampleApplication.Models
{
public class LabelDisplay
{
public List<Topic> Topics;
}
public class Topic
{
public string Description { get; set; }
public int Code { get; set; }
}
}
REFERENCE
Iterate through collection and print Index and Item in Razor
I need to display theDescription of (only) first Topic object in a label
Unless I totally misunderstood you, selecting the first item (only) in your view would look something like:
#if (Model.Topics.Any())
{
#Html.DisplayFor(x => x.Topics.First().Description)
}