How can I show two ActionResult in Home/index view MVC C# - c#

I have two controllers
BloggsController:
//Last blogg from the database
public ActionResult LastBlogg()
{
var lastblogg = db.Bloggs.OrderByDescending(o => o.ID).Take(1);
return View(lastblogg);
}
DishesController:
//Last recipe from the database
public ActionResult LastRecipe()
{
var last = db.Dishes.OrderByDescending(o => o.ID).Take(1);
return View(last);
}
I want to show the result of this on my start-page, Views/Home/index.
If I put this in my HomeController:
//Last recipe from the database
public ActionResult Index()
{
var last = db.Dishes.OrderByDescending(o => o.ID).Take(1);
return View(last);
}
Can I show the result in of recipe on my start-page but how do I show both the result of the blogg and recipe on om startpage?

You should create separate partial views for LastBlogg and LastRecipe and place both of them to your home page (new Model will be required).

Create a View Model and add both Blogg and Recipe to it.
public ActionResult Index()
{
var lastRecipe = db.Dishes.OrderByDescending(o => o.ID).Take(1);
var lastblogg = db.Bloggs.OrderByDescending(o => o.ID).Take(1);
var model = new BloggRecipeModel(lastRecipe, lastblogg);
return View(model);
}

You could simply create a custom ViewData in your Models folder, like this:
public class MyCustomViewData
{
public Dish Dish {get;set;}
public Blog Blog {get;set;}
}
Then in your controller:
ViewData.Model = new MyCustomViewData
{
Dish = db.Dishes.OrderByDescending(o => o.ID).Take(1);
Blog = db.Bloggs.OrderByDescending(o => o.ID).Take(1);
}
return View();
And in your view, set the #Model property to Models.MyCustomViewData and handle it accordingly.

Related

ViewModel Not Working

[HttpPost]
public ActionResult AddToCart(int phoneListingID, string sellerSKU)
{
ShoppingBasket shoppingBasket = new ShoppingBasket();
BasketItem currentItem = new BasketItem
{
sellerID = 1,
Price = 100,
Quantity = 1,
sellerSKU = "testsku"
};
shoppingBasket.AddtoBasket(currentItem, this.HttpContext);
var viewModel = new BasketViewModel
{
basketItems = ShoppingBasket.GetBasketItems(this.HttpContext),
basketTotal = ShoppingBasket.GetBasketTotal(this.HttpContext)
};
return View(viewModel);
}
My form:
#using (Html.BeginForm("AddToCart","ShoppingBasket",new { phoneListingID = 12345, sellerSKU = "test"}, FormMethod.Post ))
{
<input type="submit" value="AddToCart" />
}
The expected result is that my BasketViewModel page is returned, however the view being returned is ShoppingBasket/AddToCart?PhoneID=xxxx&sellerSKU=xxxx
What am I doing wrong?
In MVC Suppose your action is like
public ActionResult MyAction()
{
return View();
}
In this scenerio it will point to the view named 'MyAction'. If you want to send it to another view make it like
public ActionResult MyAction()
{
return View("MyViewName");
}
If you want to pass some model to make it like
public ActionResult MyAction()
{
return View("MyViewName",model); // Here model is your object of model class
}
In you snippet your are returning default i.e. 'AddToCart' view because you are not describing explicitly. Make your code like
return View("BasketViewModel",viewModel); // where BasketViewModel is your view name
You're returning that controller's View, if you wish to transfer to another view try
return BasketViewActionResult(viewmodel)
Then access your 'BasketViewActionResult'
Function BasketViewActionResult(model as BasketViewModel) as ActionResult
return View(model)
End Function
Sorry if you don't get VB, I can translate it to C# for you if you wish.
Edit:
You can also simply change the form's action.
#using (Html.BeginForm("BasketView","ShoppingBasket",...
and make all your manipulations within that actionresult

connecting controller with model to display results in view page

So i have this aps.net mvc project in which i created a service layer, model views, controller, and a view page. But i am having trouble displaying my results to the view page. I am starting this would by passing in a specific linq statement in the service layer so i should be able to return it to show up on the view. Here is what i have:
Service:
public IEnumerable<RoleUser> GetUsers(int sectionID)
{
var _role = DataConnection.GetRole<RoleUser>(9, r => new RoleUser
{
Name = RoleColumnMap.Name(r),
Email = RoleColumnMap.Email(r)
}, resultsPerPage: 20, pageNumber: 1);
return _role;
}
Models:
public partial class Role
{
public RoleView()
{
this.Users = new HashSet<RoleUser>();
}
public ICollection<RoleUser> Users { get; set; }
}
public class RoleUser
{
public string Name { get; set; }
public string Email { get; set; }
}
Controller:
public ActionResult RoleUser(RoleView rvw)
{
var rosterUser = new RosterService().GetUsers();
ViewBag.RosterUsers = rosterUser;
return View();
}
View:
<div>
<span>#Model.Name</span>
</div>
I am not sure what i am missing or doing wrong but any tips will be great. I basically want to return the results from the linq statement i am testing to see that the connection is correct and functionality is there before enhancing. Thanks...
Well, if I were to go off the code you've provided I would say that I'm unsure how this compiles:
public partial class Role
{
public RoleView()
{
this.Users = new HashSet<RoleUser>();
}
public ICollection<RoleUser> Users { get; set; }
}
it feels like that should be:
public partial class RoleView
and then I would say that at the top of your view you're missing this:
#model NamespaceToClass.RoleView
and then I would say you're not going to be able to issue this:
#Model.Name
because RoleUser isn't your model. You're going to need to loop through the users:
#foreach (RoleUser ru in Model.Users)
and then inside that loop you can build some HTML with this:
ru.Name
but I would also question your controller. Right now it's receiving a model to return that model. There is some code missing here but generally speaking, inside the method:
public ActionResult RoleUser(RoleView rvw)
you would actually go get the data, construct the model, and then return that:
var users = serviceLayer.GetUsers(...);
// now construct the RoleView model
var model = ...
return View(model);
Based off of our conversation you currently have something like this in your controller:
public ActionResult View(int id)
{
// get the menu from the cache, by Id
ViewBag.SideBarMenu = SideMenuManager.GetRootMenu(id);
return View();
}
public ActionResult RoleUser(RoleView rvw)
{
var rosterUser = new RosterService().GetUsers();
ViewBag.RosterUsers = rosterUser;
return View();
}
but that really needs to look like this:
public ActionResult View(int id)
{
// get the menu from the cache, by Id
ViewBag.SideBarMenu = SideMenuManager.GetRootMenu(id);
var rosterUser = new RosterService().GetUsers();
ViewBag.RosterUsers = rosterUser;
return View();
}
because you're launching this page from the sidebar which is hitting this action because you're passing the id in the URL. You don't even need the other action.

Pulling data from sql database into textfield

I have a table of students and i wanted to show the name of the student on the profile page which is stored in the students table.
This is what i have in mind for my controller:
public ActionResult StudentName(StudentModel model)
{
if(ModelState.IsValid)
{
using (var db = new SchoolDataContext())
{
var result = from s in db.Students select s.StudentName;
model.StudentName = result.ToString();
}
}
}
in my view i have:
#Html.LabelFor(s => s.StudentName)
#Html.TextBoxFor(s => s.StudentName)
my model:
public class StudentModel
{
[Display(Name = "Student Name")]
public string StudentName{ get; set; }
}
I will need a get method to get the student name to display in the textbox and at the same time have a post method so that it could be saved if changed within the same box after clicking save.
Probably your controller would look something like this:
public ActionResult StudentName(int studentId)//you can't pass a model object to a get request
{
var model = new StudentModel();
using (var db = new SchoolDataContext())
{
//fetch your record based on id param here. This is just a sample...
var result = from s in db.Students
where s.id equals studentId
select s.StudentName.FirstOrDefault();
model.StudentName = result.ToString();
}
return View(model);
}
In the get above, you can pass in an id and then fetch the record from the database. Populate your model properties with the data retrieved and pass that model into your view.
Then in the post action below, you accept the model as an argument, check the model state, and process the data. I'm showing a redirect here, but you can return any view you'd like after the post executes.
[HttpPost]
public ActionResult StudentName(StudentModel model)
{
if(ModelState.IsValid)
{
using (var db = new SchoolDataContext())
{
//update your db record
}
return RedirectToAction("Index");
}
return View(model);
}

MVC 3 - Passing model to controller from different controller

At the moment this is what I have in my HomeController:
[HttpPost]
public ActionResult Index(HomeFormViewModel model)
{
...
...
TempData["Suppliers"] = service.Suppliers(model.CategoryId, model.LocationId);
return View("Suppliers");
}
This is what I have in my SupplierController:
public ViewResult Index()
{
SupplierFormViewModel model = new SupplierFormViewModel();
model.Suppliers = TempData["Suppliers"] as IEnumerable<Supplier>;
return View(model);
}
This is my Supplier Index.cshtml:
#model MyProject.Web.FormViewModels.SupplierFormViewModel
#foreach (var item in Model.Suppliers) {
...
...
}
Instead of using TempData is there a different way to pass objects to a different controller and its view?
Why don't you just pass those two ID's in as parameters, then call the service class from the other controller? Something like:
Have your SupplierController method like so:
public ViewResult Index(int categoryId, int locationId)
{
SupplierFormViewModel model = new SupplierFormViewModel();
model.Suppliers = service.Suppliers(categoryId, locationId);
return View(model);
}
Then, I'm assuming you're calling your view from within the Supplier view via a link of some sort? You can do:
#foreach (var item in Model.Suppliers)
{
#Html.ActionLink(item.SupplierName, "Index", "Supplier", new { categoryId = item.CategoryId, locationId = item.LocationId})
//The above assumes item has a SupplierName of course, replace with the
//text you want to display in the link
}

ASP.NET MVC Show success message

Here is an example method I have that deletes a record from my app:
[Authorize(Roles = "news-admin")]
public ActionResult Delete(int id)
{
var ArticleToDelete = (from a in _db.ArticleSet where a.storyId == id select a).FirstOrDefault();
_db.DeleteObject(ArticleToDelete);
_db.SaveChanges();
return RedirectToAction("Index");
}
What I would like to do is show a message on the Index view that says something like: "Lorem ipsum article has been deleted" how would I do this? Thanks
Here is my current Index method, just in case:
// INDEX
[HandleError]
public ActionResult Index(string query, int? page)
{
// build the query
var ArticleQuery = from a in _db.ArticleSet select a;
// check if their is a query
if (!string.IsNullOrEmpty(query))
{
ArticleQuery = ArticleQuery.Where(a => a.headline.Contains(query));
//msp 2011-01-13 You need to send the query string to the View using ViewData
ViewData["query"] = query;
}
// orders the articles by newest first
var OrderedArticles = ArticleQuery.OrderByDescending(a => a.posted);
// takes the ordered articles and paginates them using the PaginatedList class with 4 per page
var PaginatedArticles = new PaginatedList<Article>(OrderedArticles, page ?? 0, 4);
// return the paginated articles to the view
return View(PaginatedArticles);
}
One way would be to use TempData:
[Authorize(Roles = "news-admin")]
public ActionResult Delete(int id)
{
var ArticleToDelete = (from a in _db.ArticleSet where a.storyId == id select a).FirstOrDefault();
_db.DeleteObject(ArticleToDelete);
_db.SaveChanges();
TempData["message"] = ""Lorem ipsum article has been deleted";
return RedirectToAction("Index");
}
and inside the Index action you could fetch this message from TempData and make use of it. For example you could pass it as a property of your view model which will be passed to the view so that it can show it:
public ActionResult Index()
{
var message = TempData["message"];
// TODO: do something with the message like pass to the view
}
UPDATE:
Example:
public class MyViewModel
{
public string Message { get; set; }
}
and then:
public ActionResult Index()
{
var model = new MyViewModel
{
Message = TempData["message"] as string;
};
return View(model);
}
and inside the strongly typed view:
<div><%: Model.Message %></div>

Categories

Resources