Returning a Model to View from Action - c#

I am new to ASP.NET MVC Web Applications.
I am getting the following Error when I try to access:
http://localhost:1160/View/ViewMovies
ViewMovies is an Action that returns a Model to View. Likewise, I have a similar Action named ViewCustomers, which is also giving me the same error.
Error
ViewController.cs
public class ViewController : Controller
{
// GET: View
public ActionResult Index()
{
return View();
}
private MovieCustomerViewModel model = new MovieCustomerViewModel();
public ActionResult ViewMovies()
{
model.movies = new List<Movie> {
new Movie{id=1,name="Shrek"},
new Movie{id=1,name="Wall-e"}
};
return View(model);
}
public ActionResult ViewCustomers()
{
model.customers = new List<Customer> {
new Customer{id=1,name="Junaid"},
new Customer{id=1,name="Zohaib"}
};
return View(model);
}
}
I have added a view folder named Movie_Customer:
It has two separate .cshtml files named, Customers.cshtml and Movies.cshtml
Customers.cshtml
#model Ex1.ViewModels.MovieCustomerViewModel
#{
ViewBag.Title = "Customers";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Customers</h2>
<table class="table table-bordered table-hover" />
<tr>
<th>ID</th>
<th>Name</th>
</tr>
#{
foreach (var v in Model.customers)
{
<tr>
<td>v.id</td>
<td>v.name</td>
</tr>
}
}
Movies.cshtml
#model Ex1.ViewModels.MovieCustomerViewModel
#{
ViewBag.Title = "Movies";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Movies</h2>
<table class="table table-bordered table-hover" />
<tr>
<th>ID</th>
<th>Name</th>
</tr>
#{
foreach (var v in Model.movies)
{
<tr>
<td>v.id</td>
<td>v.name</td>
</tr>
}
}
I am doing exactly what's done here: http://techfunda.com/howto/240/return-model-to-view-from-action-method
What am I doing wrong?
How do I remove these errors?
What should I must know about handling Views or View Models?
Thanks in advance.

Your controller is named ViewController and by convention the framework will check the ~Views/<ControllerNamePrefix>/ directory and Views/Shared/ directory for a view file matching the name that youre requesting (here you're requesting ViewCustomers and ViewMovies since you are using return View(model) the framework will look for a view with a name that matches the action. If you want to specify the name of the view then use return View("ViewName", model))
To resolve your error, you can rename your view to ViewCustomers.cshtml and ViewMovies.cshtml and put those files in a new directory: location /Views/View/.
Personally, I'd recommend renaming your controller as well since ViewController doesn't really say anything about what the controller should be responsible for. In MVC applications, most all controllers will be returning views.
In summary:
You're requesting views named ViewCustomers.cshtml and ViewMovies.cshtml which don't exist in any folder.
Your views are not located in the write
subdirectory in the Views folder for the framework to be able to find
them.

I think you are confused because when trying to return a view from controller you have to take the literal name and place it in the return overflow as
return View("Customer",model)
Or when constructing a controller you might want right click the name of the controller and select the option "Create view" for the selected controller, this would automatically bind those two together.
Views don't share the same naming convention as controllers

Related

See ASP.NET MVC Index page in C# be populated with data from model without ID in the URL

In my application I am using Entity Framework 6 and ASP.NET MVC in C#.
I have a table that has records that I plan on populating my Index page with. How do I populate the index page without having the system add the id of the record to the URL. See example below. I have already looked at routing but with adding custom route you are forced to add more text to the url when all I want is the URL to show up as example.com. I don't want and don't need example.com/MenuRecords/Details/20 for a user to see.
So example.com should load the following data from the model below in the index view of the HomeController.
index.cshtml page calling the model data shown below:
#model example.Models.tblMenuRecords
#Model.ThisWeeksBestDrink
#Model.ThisWeeksBestAppetizer
#Model.ThisWeeksBestDesert
#Model.ThisWeeksBestLunchSpecial
This is the cntroller action method:
public ActionResult Index()
{
return View();
}
How do I get that to work properly for the Index page? Since this is the home page that is calling data from a model I cannot have the URL have anything other than example.com .... but I do understand that when calling data from a model you do need some sort of ID but I just do not really understand how to do that.
I know that there is the route config that includes this default route that allows you to show only the name of the domain...But how is this done when you are trying to load data from the database.
routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }
Is this the correct way to pass an instance of the tblMenuRecords to the view?
public ActionResult Index()
{
tblMenuRecords tblMenuRecords = db.tblMenuRecords();
return View(tblMenuRecords);
}
I think you have to fix the action
public ActionResult Index()
{
tblMenuRecords tblMenuRecords = db.tblMenuRecords.FirstOrDefault();
return View(tblMenuRecords);
}
I think your view is missed with model. View code should be like below
#model Models.MenuRecords
#{
ViewBag.Title = "Menu Records";
}
<h2>Details</h2>
<div>
<h4>Menus</h4>
<hr />
<table>
<tr>
<td>
#Html.DisplayFor(model => model.ThisWeeksBestDrink)
</td>
<td>
#Html.DisplayFor(model => model.ThisWeeksBestLunchSpecial)
</td>
</tr>
</table>
</div>
I hope, it will help you.

in asp.net mvc im trying to create a view for the list of the users that are signing in

im using the folders that are supplied with the asp.net web application .net framework , and I'm trying to create a view fo the users that are signing in but it doesn't work even that I did manage to create a view for the roles, I did the same thing with the users but here it just doesn't work
here is the controller code
public ActionResult Index( )
{
var Users = context.Users.ToList();
return View(Users);
}
here is the view
#model List<A11_RBS.Models.ApplicationDbContext>
....
<table class="table">
<tr>
<th>#Html.DisplayNameFor(DbModel => Model)</th>
</tr>
#if (Model.Count() == 0)
{
<tr>
<td colspan="7">No records match search criteria</td>
</tr>
}
else
{
foreach (var item in Model)
{
<tr>
<td>#Html.DisplayFor(DbModel =>item.Users)</td>
</tr>
}
}
</table>
the error is :
The model item passed into the dictionary is of type 'System.Collections.Generic.List'1[A11_RBS.Models.ApplicationUser]', but this dictionary requires a model item of type 'System.Collections.Generic.List'1[A11_RBS.Models.ApplicationDbContext]'.
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.
My guess is the problem in the model but I don't know what to do about it
change ApplicationDbContext to ApplicationUser as suggested by the exception
you are sending an applicationUser model to the view but you are trying to use it as an ApplicationDbContext.
var Users = context.Users.ToList();
return View(Users);

Best way to handle add/view/delete on one page

What I want to do
I am very new to MVC.
I'm trying to create a page that allows users to perform the following actions on the same page:
View the list (table)
Add a new item (Filling the form and clicking the Add button should update the table)
Delete an item from the list (Clicking the Delete button in a row should update the table)
A simple example looks like this but I actually have two lists on one page (Fees and Costs):
Question
What would be the best way to achieve this?
Should I go with Dylan Beattie's method posted here which would look something like this?
public ActionResult MyAction(string submitButton, MyViewModel form)
{
switch (submitButton)
{
case "AddFee":
return (AddFee(form));
case "AddCost":
return (AddCost(form));
case "RemoveFee":
return (RemoveFee(form));
case "RemoveCost":
return (RemoveCost(form));
}
}
public ActionResult AddFee(MyViewModel form)
{
Fee newFee = ....; // Get entered data from `form`
_repository.InsertFee(newFee);
return View("Create"); //Back to the original page
}
Or is there any other recommended methods to handle this such as using JavaScript?
You could create the table as a partial view and re render this via ajax.
Wrap the partial view in a div and Wrap the form in #using (Ajax.BeginForm(.... and target the wrapper div. Your controller action that is targeted by the ajax request will need to return a partial view.
Here is a simple example
public class HomeController : Controller
{
public ActionResult Index()
{
MYvm vm = new MYvm() { id = 1, name = "This is my View Model" };
return View(vm);
}
public ActionResult DA(MYvm vm)
{
vm.name = "CHANGED";
return PartialView("Part", vm);
}
View:
#model MvcApplication1.Controllers.HomeController.MYvm
#{
ViewBag.Title = "Home Page";
}
#using (Ajax.BeginForm("DA", "Home", new AjaxOptions() { UpdateTargetId = "cont", HttpMethod = "Get" }))
{
<div>
Id: #Html.EditorFor(model => model.id)
</div>
<div>
Name: #Html.EditorFor(model => model.name)
</div>
<input type="submit" value="SubmitForm" />
}
<div id="cont">
#{Html.RenderPartial("part", Model);}
</div>
Partial View
#model MvcApplication1.Controllers.HomeController.MYvm
#{
ViewBag.Title = "part";
}
<h2>part</h2>
#Model.name
Should I go with [previous SO answer]
No. That answer was for a different scenario where the question had a form with two submit buttons that wanted to do two different actions (and wasn't even the accepted answer to that question).
Your sample screenshot indicates that some javascript/jquery and ajax would solve the issue cleanly.
As you're new to MVC, try to keep it relatively simple. Break up the page into separate parts:
the containing page
the edit form
the list with remove
the edit/list work independently and should be written in a way that they could be put on any other page - the page is just there to contain them and doesn't do much else (obviously your real page will contain more, but add those parts as separate components as well).
1 Create actions for your list and edit forms that return partialviews - just the parts that are needed for that view (self-contained)
controller:
[HttpGet]
public ActionResult AddCost()
{
var model = new Cost();
return PartialView(model);
}
[HttpPost]
public void AddCost(Cost model)
{
if (ModelState.IsValid) {
db.SaveCost(model);...
}
}
form Views/Home/AddCost.cshtml:
#using (Ajax.BeginForm(...
{
<div class='editor-label'>#Html.LabelFor(model=>model.Description)</div>
...etc...
}
I'll leave you to set the Ajax.BeginForm properties. But make sure the on-success calls reloadCostList() (see below)
controller
public ActionResult CostList()
{
var model = db.loadCosts(); ...
return PartialView(model);
}
list, Views/Home/CostList.cshtml
#model IEnumerable<ViewModels.Cost>
<table>
<thead>
<tr>
<th>Cost Description</th>
...
<tbody>
#foreach (var cost in Model.Costs)
{
<tr data-id='#cost.Id'>
<td>#Html.DisplayFor(x=>cost.Description)</td>
...
<td><a href='#' class='remove-button'>Remove</a></td>
}
...
2 Create an action + view for the main page with placeholder for the form and calls the list partial-action, eg:
<div id="body">
<div id="formWrapper">
#Html.Action("AddCost")
</div>
<div id="listWrapper">
#Html.Action("ListView")
</div>
</div>
if you already load the data for the page, you can pass it directly to the partial, but there's no need:
#Html.Partial("ListView", Model.Costs)
this allows you to refresh the list via an ajax call, something like:
function reloadCostList() {
$(".listWrapper").load("Home/CostList");
}
(ideally, $.ajax and add some fancy UI to indicate loading)
3 Add a remove action to your controller
[HttpPost]
public void RemoveCost(int id)
{
}
4 Wire up the Remove link
$(function() {
$(".remove-button").click(function() {
var id = $(this).closest("tr").attr("id");
$.post("/Home/RemoveCost/" + id, null, function() {
$(".listWrapper").load("Home/CostList");
// or reloadCostList(); from above
// or:
//$(".listWrapper tr[id=" + id + "]").hide();
});
});
}
rather than re-load the entire list, you could just remove the row (add some fancy UI like fade-out...)

MVC4 get table data from view to controller

How can I get the data which is bottom left hand side of the image from view to controller when I press to submit button ?
Link for image
public ActionResult EnterInformation1()
{
// the ??? is the data from the view;
TempData['abc'] = ???
return RedirectToAction("Paper");
}
I did look up reference before I ask.thanks
If you want to send data from view to controller all you need is to do next step:
1) Send data from controller to view. For example you want to display the content of a model wich is List
public ActionResult ShowList()
{
List<string> lst = new List<string>() {"1", "2", "3", ,"4"};
return View("MyListView", lst);
}
2) Display this data on the View using html helpers with postfix "for" (for example, textBoxFor, hiddenFor, EditorFor, DisplayFor...) and place them inside form tag
#model List<string>
<form action="GetDataFromView" method="post">
<table>
<tr>
<th>some header</th>
<tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(m=> item)
</td>
</tr>
}
</table>
</form>
3) Write Method in controller wich will get these data
public ActionResult GetDataFromView(List<string> model)
{
//do what you want with data sended from view to controller
// which stored in parameter model
return View("someView");
}

Display GUID in MVC 5 View?

So I am following the example at http://holsson.wordpress.com/2011/08/24/microsoft-dynamics-crm-2011-online-integration-getting-started-late-bound/ to try and create an MVC 5 site that uses CRM as the backing data. I created a CRMAccount Controller (Could't make one called Account as it was used by the Identity system).
I am able to successfully query the CRM System but when i try to use the Razor Code below in my view, I get the name, but nothing under the accountid is displayed. The item returned by accountid is a GUID, If I try to set it to a string, the DisplayFor complains that it can't render that.
#model IEnumerable<Microsoft.Xrm.Sdk.Entity>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<table>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item["accountid"])
</td>
<td>
#Html.DisplayFor(modelItem => item["name"])
</td>
</tr>
}
</table>
I am only doing this right now for Proof Of Concept. Eventually, I want to put the two together as a drop down box, but if I can't get the GUID to pull correctly, I'm going to have problems.
EDIT:-------------------------------------------------------------------
I was asked to post the controller code, though something similar was in the example i linked to above.
Here's the code used in my controller.
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
namespace ExternalEntities.Controllers
{
public class CRMAccountController : Controller
{
// GET: CRMAccount
public ActionResult Index()
{
var service = Session["ServiceProxy"] as IOrganizationService;
if (service != null)
{
var context = new OrganizationServiceContext(service);
IQueryable<Entity> query = from e in context.CreateQuery("account") select e;
List<Entity> accts = query.ToList();
return View(accts);
}
return RedirectToAction("Login", "Account");
}
}
}
try
#Html.DisplayFor(modelItem => item.accountid)
instead of
#Html.DisplayFor(modelItem => item["accountid"])
for intellisense, also can you show the controller please.
Edited after some comments back and forth:
Maybe you have a DisplayTemplate that is on your way? Try to do #item["accountid"] and see if it still blank. (not using DisplayFor)

Categories

Resources