Hi This is my Action method
public ActionResult Welcome(string name, int numTimes=1)
{
var customerEntityColl = new EntityCollection(new CustomerEntityFactory());
var customerEntity = new CustomerEntity(1);
using(var adapter = new DataAccessAdapter())
{
adapter.FetchEntityCollection(customerEntityColl,null);
}
return View(customerEntityColl);
}
and this is my View
#model Data.HelperClasses.EntityCollection<Data.EntityClasses.CustomerEntity>
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
#{
}
<p>This is our welcome view and the sender name is #ViewBag.Name and sent #ViewBag.NumTimes times this request</p>
#foreach (var item in Model)
{
<p>#Html.DisplayFor(modelItem=> item.FirstName)</p>
}
Now when I run this action method it gives me below error, can somebody please help to fix it..
The model item passed into the dictionary is of type
'Data.HelperClasses.EntityCollection', but this dictionary requires a
model item of type
'Data.HelperClasses.EntityCollection`1[Data.EntityClasses.CustomerEntity]'.
Thanks
Yes, you're instantiating EntityCollection, and not EntityCollection<CustomerEntity>() which is what the model expects.
You can just replace new EntityCollection(new CustomerEntityFactory()) with new EntityCollection<CustomerEntity>(); (assuming you didn't change any behavior in the CustomerEntityFactory)
Additionally, you should fetch the entity with a Predicate, this is not doing anything at the moment when you're using the adapter model:
var customerEntity = new CustomerEntity(1);
and this will just fetch all the customers in the database:
adapter.FetchEntityCollection(customerEntityColl,null);
Related
I would like to setup gridview under MyTickets tab.
How can I set this view to have only tickets from username eg 'testuser' ?
In controller I have below code. Table Zgloszenia is my table where I storing all information about tickets (date,username, id etc)
public ActionResult MyTickets(Zgloszenia model)
{
if (Session["UserID"] != null)
{
test dg = new test();
var item = dg.Zgloszenia.Where(x => x.UsrUsera == model.UsrUsera).SingleOrDefault();
return View(item);
}
else
{
return RedirectToAction("Login");
}
}
In view I have this code:
#model IEnumerable<Webform.Models.Zgloszenia>
#{
ViewBag.Title = "MyTickets";
WebGrid grid = new WebGrid(Model);
}
<h2>MyTickets</h2>
#if (Session["UserID"] != null)
{
<div>
Welcome: #Session["Username"]<br />
</div>
}
#grid.GetHtml(columns: new[] {
grid.Column("Opis"),
grid.Column("Priorytet"),
grid.Column("Srodowisko"),
grid.Column("NumerTaska"),
grid.Column("test"),
grid.Column("Date")
})
When I log in to my app and click Tab "MyTicket" I'm receiving below error:
A data source must be bound before this operation can be performed.
How I can fix this issue and set up view properly ?
In your action you are selecting a single item, not a collection to enumerate. On the contrary, the WebGrid expects a collection as a data source, so the way you declared things on the view is fine.
To check if that is indeed the issue, simply remove SingleOrDefault call in your action. If your Where call returns at least one record, you should be able to see it on the page:
test dg = new test();
var items = dg.Zgloszenia.Where(x => x.UsrUsera == model.UsrUsera).ToList();
return View(items);
Are you working with Visual studio? If yes, you have to make a dataset. (local or online) You do not have a database at the moment so he saves it nowhere.
I have a PartialView (_Letra) that receives information from a Controller named Music ... this way
public ActionResult CarregarLetra(string id, string artista, string musica)
{
return PartialView("_Letra", ArtMus(artista, musica));
}
public ResultLetra ArtMus(string artista, string musica)
{
//Conteúdo do metodo[..]
var queryResult = client.Execute<ResultLetra>(request).Data;
return queryResult;
}
Until then, no problem. What happens is that now I need to pass other information to this same PartialView (_Letra). This information is in PartialView (_Cifra).
So I added the following lines in my Music controller
public ActionResult CarregarCifra(string id, string artista, string musica)
{
return PartialView("_Cifra", GetCifra(artista, musica));
}
public ResultChords GetCifra(string artista, string musica)
{
var cfrTest= new Cifra();
var cifra = new ResultChords();
cifra.chords = cfrTest.GetInfs(artista, musica);
return cifra;
}
Everything working so far, PartialView _Cifra receives the information
I searched and found that I could use in PartialView _Letra the Html.Partial to load my PartialView _Cifra, I did this way then
I added
<div class="item">
<div class="text-carousel carousel-content">
<div>
#Html.Partial("_Cifra", new letero.mus.Infra.Models.ResultChords());
</div>
</div>
</div>
Now it starts to complicate why, the return of this is null, I believe it is due to a new instance of ResultChords that I make in Html.Partial
I have already tried using a ViewBag also to transpose the information between Partials, but probably not correctly, due to the return being null as well.
I've already done a lot of research and I'm not getting the information I need for PartialView _Letra.
There is a better way not to use Html.Partial, or to use it properly, as I am not aware.
In _Letra use
#Html.Action("CarregarCifra", "Music", new { id=Model.Id, artista=Model.Artista, musica=Model.Musica });
if the variables are available on the model then you can pass them in; otherwise, make use of the Viewbag and set them in CarregarLetra
Are you always passing a new object to the second partial? You could just create it at the top of the new _Cifra partial.
_Cifra.cshtml
#{
var resultChords = new letero.mus.Infra.Models.ResultChords();
}
I don't think my question is unique but I will ask as there might be some peculiarities with regards to my question. I have a Business Model that loads files from a folder with and displays them on a webpage for editing and other desired operations. My controller calls on this model like so:
This is the method that handles the listing of files and returns an enumeration of fileinfo objects
public IEnumerable<FileInfo> ListUploadedFiles(HttpContextBase htc)
{
//list all the files from the upload directory
var path = htc.Server.MapPath("~/FileUpload");
var di = new DirectoryInfo(path);
return di.EnumerateFiles();
}
This is the code in the controller action that should populate a viewmodel and pass the viewmodel a view which is where I am having a bit of an issue.
var viewmodel = new List<UploadedImageViewModel>();
var files = uploader.ListUploadedFiles(context);
foreach (var item in files)
{
viewmodel.Add(new UploadedImageViewModel()
{
ImageName = item.Name,
CreatedOn = item.CreationTime,
ImageSize = item.Length,
FileType = item.Extension
});
}
return View("ListFiles", viewmodel);
Now in my view I do this to list out the desired properties on the view:
#using SeeSite.Models
#model IEnumerable<UploadedImageViewModel>
#{
ViewBag.Title = "Upload";
}
#foreach(UploadedImageViewModel items in Model)
{
<li>#items.ImageName <span>Details</span>
<span>Rename</span>
</li>
}
but I keep getting an exception:
System.NullReferenceException: Object reference not set to an instance
of an object.
And points to the line where my foreach begins. Now just to clear things up, if I use ViewBag it works fine though I can only access the details of one file, but using a viewmodel just doesn't work. Been stuck here for a whole day and don't want to waste anymore time. What could be wrong?!
Oh and if I do this in the view:
#foreach (var dir in new DirectoryInfo(Server.MapPath("~/FileUpload"))
.EnumerateFiles())
{
<li>#dir.Name <span>|</span>Details
<span>|</span> Rename</li>
}
it works. So am I missing something here or is this the best solution to do what I am trying to do?
In my mvc solution I was originally using a viewModel to hold an IEnumerable of SelectListItems. These would be used to populate a dropdownfor element like below
#Html.DropDownListFor(model => model.Type, Model.PrimaryTypeList, new { data_acc_type = "account", data_old = Model.Type, #class = "js-primary-account-type" })
the problem being that whenever I had to return this view, the list would need re-populating with something pretty heavy like the following:
if(!ModelState.IsValid){
using (var typeRepo = new AccountTypeRepository())
{
var primTypes = typeRepo.GetAccountTypes();
var primtype = primTypes.SingleOrDefault(type => type.Text == model.Type);
model.PrimaryTypeList =
primTypes
.Select(type => new SelectListItem()
{
Value = type.Text,
Text = type.Text
}).ToList();
}
return View(model);
}
It seemed silly to me to have to rewrite - or even re-call (if put into a method) the same code every postback. - the same applies for the ViewBag as i have about 6 controllers that call this same view due to inheritance and the layout of my page.
At the moment i'm opting to put the call actually in my razor. but this feels wrong and more like old-school asp. like below
#{
ViewBag.Title = "Edit Account " + Model.Name;
List<SelectListItem> primaryTypes = null;
using (var typeRepo = new AccountTypeRepository())
{
primaryTypes =
typeRepo.GetAccountTypes()
.Select(t => new SelectListItem()
{
Value = t.Text,
Text = t.Text
}).ToList();
}
#Html.DropDownListFor(model => model.Type, primaryTypes, new { data_acc_type = "account", data_old = Model.Type, #class = "js-primary-account-type" })
Without using something completely bizarre. would there be a better way to go about this situation?
UPDATE: While semi-taking onboard the answer from #Dawood Awan below. my code is somewhat better, still in the view though and i'm 100% still open to other peoples ideas or answers.
Current code (Razor and Controller)
public static List<SelectListItem> GetPrimaryListItems(List<AccountType> types)
{
return types.Select(t => new SelectListItem() { Text = t.Text, Value = t.Text }).ToList();
}
public static List<SelectListItem> GetSecondaryListItems(AccountType type)
{
return type == null?new List<SelectListItem>(): type.AccountSubTypes.Select(t => new SelectListItem() { Text = t.Text, Value = t.Text }).ToList();
}
#{
ViewBag.Title = "Add New Account";
List<SelectListItem> secondaryTypes = null;
List<SelectListItem> primaryTypes = null;
using (var typeRepo = new AccountTypeRepository())
{
var primTypes = typeRepo.GetAccountTypes();
primaryTypes = AccountController.GetPrimaryListItems(primTypes);
secondaryTypes = AccountController.GetSecondaryListItems(primTypes.SingleOrDefault(t => t.Text == Model.Type));
}
}
In practice, you need to analyse where you app is running slow and speed up those parts first.
For starters, take any code like that out of the view and put it back in the controller. The overhead of using a ViewModel is negligible (speed-wise). Better to have all decision/data-fetching code in the controller and not pollute the view (Views should only know how to render a particular "shape" of data, not where it comes from).
Your "Something pretty heavy" comment is pretty arbitary. If that query was, for instance, running across the 1Gb connections on an Azure hosted website, you would not notice or care that much. Database caching would kick in too to give it a boost.
Having said that, this really is just a caching issue and deciding where to cache it. If the data is common to all users, a static property (e.g. in the controller, or stored globally) will provide fast in-memory reuse of that static list.
If the data changes frequently, you will need to provide for refreshing that in-memory cache.
If you used IOC/injection you can specific a single static instance shared across all requests.
Don't use per-session data to store static information. That will slow down the system and run you out of memory with loads of users (i.e. it will not scale well).
If the DropDown Values don't change it is better to save in Session[""], then you can access in you View, controller etc.
Create a class in a Helpers Folder:
public class CommonDropDown
{
public string key = "DropDown";
public List<SelectListItem> myDropDownItems
{
get { return HttpContext.Current.Session[key] == null ? GetDropDown() : (List<SelectListItem>)HttpContext.Current.Session[key]; }
set { HttpContext.Current.Session[key] = value; }
}
public List<SelectListItem> GetDropDown()
{
// Implement Dropdown Logic here
// And set like this:
this.myDropDownItems = DropdownValues;
}
}
Create a Partial View in Shared Folder ("_dropDown.cshtml"):
With something like this:
#{
// Add Reference to this Folder
var items = Helpers.CommonDropDown.myDropDownItems;
}
#Html.DropDownList("ITems", items, "Select")
And then at the top of each page:
#Html.Partial("_dropDown.cshtml")
I have this code, which creates a new "incident" partial and displays it BEFORE the last one. Is there a way to tell it to display it AFTER instead?
#{
foreach (var incident in Model.allIncidents.ToList())
{
Model.newIncident = incident;
#Html.Partial("IncidentBodyPartial", Model)
}
}