Display GUID in MVC 5 View? - c#

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)

Related

Returning a Model to View from Action

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

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);

WebAPI2 / Angular job Interview skill assessment [SHARE] - NULL values

A few months back, there was a job position who required a pre interview task assessment. I'm actually new to .NET, so I passed and decided to apply to another job which didn't require .net as much. Long story short. Since then, the idea of solving this problem hunts me and It bothers me that I was able to get really close to the solution and didn't actually finished it.
So, if anybody wants to practice their .net /webapi2/ angular skills here it is:
screenshot
I get a weird error (NULL values) when I'm almost finishing this task
My Homecontroller.cs
namespace KLab.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Home Page";
return View();
}
public JsonResult GetSections()
{
var db = new KLabDBEntities();
var samples = db.Samples.Include("User").Include("Status").ToList();
return Json(samples, JsonRequestBehavior.AllowGet);
}
}
}
Since this is WEb API I've changed the angular code to the following:
my App.js
var myApp = angular.module('myApp', []);
myApp.controller('maincontroller', function ($scope, SampleService) {
getSamples();
function getSamples() {
SampleService.getSamples()
.success(function (Samples) {
$scope.Samples = Samples;
});
}
});
my service.js
myApp.factory('SampleService', ['$http', function ($http) {
var urlBase = 'http://localhost:35656/api';
var SampleService = {};
SampleService.getSamples = function () {
return $http.get(urlBase + '/Samples');
};
return SampleService;
}]);
My index.cshtml
<h2>Samples</h2>
<div ng-controller="maincontroller">
<table class="table">
<tr>
<th>Samples Id </th>
<th>Code Number</th>
<th>Date </th>
<th>User Id </th>
<th>Status Id </th>
</tr>
<tr ng-repeat="Sample in Samples">
<td>{{Sample.SampleId}} </td>
<td>{{Sample.CodeNumber}} </td>
<td>{{Sample.Date.replace('/Date(','').replace(')/','') | date:"MM/dd/yyyy"}} </td>
<td>{{Sample.UserId}}</td>
<td>{{Sample.StatusId}}</td>
</tr>
</table>
</div>
Everything else is default from the WeBAPI2 template from Visual Studio.
so my Models are generated by Entity Framework:
When I build i get:
Samples Id CodeNumber Date UserId StatusId
data data data 1 6
data data data 2 4
My goal is to change those id numbers to the actual data of the tables , they are foreign key values
I get no values in that column and when I call the JSON I get:
[{"SampleId":1,"CodeNumber":129076,"Date":"2015-01-02T00:00:00","UserId":6,"StatusId":3,"Status":null,"User":null},
{"SampleId":2,"CodeNumber":850314,"Date":"2015-06-15T00:00:00","UserId":7,"StatusId":3,"Status":null,"User":null},
{"SampleId":3,"CodeNumber":176033,"Date":"2015-07-31T00:00:00","UserId":7,"StatusId":0,"Status":null,"User":null},
{"SampleId":4,"CodeNumber":129629,"Date":"2015-01-21T00:00:00","UserId":3,"StatusId":0,"Status":null,"User":null},"
which is odd since , Status and user are null
Somebody has suggested that this "joins" must be done within a view on the Database itself and then should be called with angular. like a SQL view or using LINQ. Unfortunately, I do not know LINQ but I do know SQL I guess I can create a view with all the tables. Therefore the question is. How can i replace those ID values to the actual data that are related to those foreign keys (userid, statusid) ?
Here's the bulk data's screenshot:
bulk data

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");
}

MVC Entity Framework using a nested foreach in view

I'm passing 3 sets of data through to a view in a viewmodel and have a problem relating one of them to the other two in my foreach coding:
My DB tables are:
"ServiceGroups" is parent to "Services"
"Services" is related through a joining table (using a 2 composite Primary Key) to the aspnet_users table (I call "Users")
I pulled this into an EF model called GWServices.edmx
so now I have 3 entities related like so:
ServiceGroup (parent to) Service
Service (many to many with) User
Then I created a controller and a viewmodel like this:
{
public class ServicesViewModel
{
public ServicesViewModel(List<ServiceGroup> servicegroups, List<Service> services, List<User> aspnetusers)
{
this.ServiceGroups = servicegroups;
this.Service = services;
this.AspnetUsers = aspnetusers;
}
public List<ServiceGroup> ServiceGroups { get; set; }
public List<Service> Service { get; set; }
public List<User> AspnetUsers { get; set; }
}
public class ClientServicesController : Controller
{
public ActionResult Index()
{
GWEntities _db = new GWEntities();
var servicegroups = _db.ServiceGroupSet.ToList();
var services = _db.ServiceSet.ToList();
var aspnetusers = _db.UserSet.ToList();
return View(new ServicesViewModel(servicegroups, services, aspnetusers));
}
}
}
Next I created the view with 3 foreach loops to:
Get and present as a UL, a list of all service groups in the database (which worked)
Populate a table under each Servicegroup filling down some Service data for each Service within that given group (which also work)
Test whether the user is associated with this particular Service, if so show only the red cross icon, otherwise show the green "select me" icon. (this doesn't populate any users)
So the code looks like this:
<% foreach (var servgroup in Model.ServiceGroups) { %>
<ul> <%= servgroup.ServiceGroupName%> </ul>
<table>
<% foreach (var serv in servgroup.Service)
{ %>
<tr>
<td class="td1">
<%= serv.ServiceDescription%>
</td>
<td class="td2">
<% = Html.Encode(String.Format("{0:f}",serv.MonthlyPrice)) %>
</td>
<td class="td3">
<%foreach (var user in serv.User) {%>
<%if (user.UserName == User.Identity.Name)
{ %>
<img src="/Content/LightRedCross_2.png" alt="" height="15px" width="15px"/>
<% }
else
{%>
<img src="/Content/LightGreenAdd_2.png" alt="" height="15px" width="15px"/>
<%} %>
<%} %>
</td>
</tr>
<% } %>
</table>
<% } %>
Can anyone tell me why foreach(var user in serv.user) does not recognise that "Customer1" (the currently logged in user) has 6 services ordered (as it is in the joining table)?
Thanks!
Paul
Looking at your code I think this could be resolved by loading the child tables of ServiceGroups.
It is likely that the Services & User reference was not loaded in the original Entity Framework query. Therefore, as you are trying to iterate through the children in the foreach loop, it does not see a collection, it just sees null.
You should try altering your retrieval statements:
_db.ServiceGroupSet.ToList()
to
_db.ServiceGroupSet.Include("ServiceSet").Include("UserSet").ToList()
If this doesn't fix your issue, I would put a break point on the below line of code and traverse the List to see if it has the data you expect.
this.ServiceGroups = servicegroups;
For starters, username comparisons are generally case-insensitive. So this:
<%if (user.UserName == User.Identity.Name)
...should be:
<%if (user.UserName.Equals(User.Identity.Name, StringComparison.OrdinalIgnoreCase))
You also have a bug where you don't dispose your entity context. You should override Controller.Dispose and dispose it there. This allows the view to render before the context is disposed.

Categories

Resources