MVC 4 WebGrid C# Error - c#

I am trying to populate a web grid view with static data but I am not having any luck.
I always get the error:
"A data source must be bound before this operation can be performed".
I understand where the error is coming from by setting up breakpoints. Basically, when the page is loaded up, the code never accesses the Account() function. Since it doesn't do that, allFiles is never initialized and returned.
Would the best way to do this be to call Action() from the View and initialize all files? I've read other questions regarding the same error but no one highlighted the fact that the code is not accessing the controller function.
Here is the Controller:
public ActionResult Account()
{
FileModel file = new FileModel();
List<FileModel> allFiles = new List<FileModel>();
file.FileID = "1";
file.UserID = "1";
var data = allFiles;
return View(data);
}
Here is the Model
public class FileModel
{
public string FileID { get; set; }
public string UserID { get; set; }
public string FileName { get; set; }
public string AddedOn { get; set; }
public int Downloads { get; set; }
public int Show { get; set; }
}
Here is the View
#model IEnumerable<GridTest1.Models.FileModel>
#{
ViewBag.Title = "Files";
WebGrid grid = new WebGrid(Model);
}
<h2>People</h2>
#grid.GetHtml(columns: new [] {
grid.Column("FileID"),
grid.Column("UserID")
})

your controller coding order is wrong. Check the following code
public ActionResult Account()
{
// Assign a value to class
FileModel file = new FileModel();
file.FileID = "1";
file.UserID = "1";
file.FileName = "Text.txt";
file.AddedOn = "AddedOn";
// Create instance for all file
List<FileModel> allFiles = new List<FileModel>();
// Add file model to list
allFiles.Add(file);
// Pass the file list to view
return View(allFiles);
}
View
#model List<GridTest1.Models.FileModel>
#{
ViewBag.Title = "Files";
WebGrid grid = new WebGrid(Model);
}
#grid.GetHtml(columns: new[] {
grid.Column("FileID"),
grid.Column("UserID"),
grid.Column("FileName"),
grid.Column("AddedOn"),
})
This will work

Related

.NET MVC: How in <a #Url.Action()> to send an Object In an Object?

Good for all :)
I want to easily submit a model for data filtering.
For quick sorting, I wrote tags by which the data will be sorted...
When I click on the link, the address bar becomes like this -> "&FilterData=Project.Web.Models.FilterData"
localhost/User?PageNum=1&SortOrder=NameAsc&FilterData=Project.Web.Models.FilterData
First Name
Here is the code for understanding)
FilterRequest.cs
public class FilterRequest
{
public int PageNumber { get; set; } = 1;
public SortType SortOrder { get; set; } = SortType.None;
public FilterData FilterData { get; set; }
}
FilterData.cs
public class FilterData
{
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
}
How can You see the FilterData field is an object. Its fields are not displayed?
And this is how I receive data into the controller)
UserController.cs
public class UserController : Controller
{
public IActionResult Index(FilterRequest request)
{
}
}
Please help me figure it out.. Display data from nested object :)
When I click on the link, the address bar becomes like this -> "&FilterData=Project.Web.Models.FilterData"
How in to send an Object In an Object?
To achieve your requirement of passing complex data to controller action via <a> tag, and make model binding work well, you can try following code snippet.
#{
ViewData["Title"] = "Home Page";
var pagination = 1;
var sort = SortType.NameAsc;
var filter = new FilterData { FirstName = "fn", MiddleName = "mn", LastName = "ln" };
var parms = new Dictionary<string, string>
{
{ "PageNumber", pagination.ToString() },
{ "SortOrder", SortType.NameAsc.ToString() },
{ "FilterData.FirstName",filter.FirstName},
{ "FilterData.MiddleName",filter.MiddleName},
{ "FilterData.LastName",filter.LastName}
};
}
<a asp-controller="Home" asp-action="Index" asp-all-route-data="parms">First Name</a>
The QueryString may look like this:
?PageNumber=1&SortOrder=NameAsc&FilterData.FirstName=fn&FilterData.MiddleName=mn&FilterData.LastName=ln
Test Result

Select tag helper from database ASP.NET Core 3.1

Ok, I'm trying to do a proper dropdown in Core 3.1. In this example https://learn.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms?view=aspnetcore-3.1#the-select-tag-helper
Model has a new list with hardcoded values
public string Country { get; set; }
public List<SelectListItem> Countries { get; } = new List<SelectListItem>
{
new SelectListItem { Value = "MX", Text = "Mexico" },
new SelectListItem { Value = "CA", Text = "Canada" },
new SelectListItem { Value = "US", Text = "USA" },
};
I looked for examples where the list is coming from the database but they are very inconsistent. The only way I was able to do the dropdown list is with the ViewBag which is not advised.
I have two models. 1.
public partial class Glossary
{
public int UniqueId { get; set; }
public int Category { get; set; }
public string DisplayText { get; set; }
}
which is my view model
public partial class AdminUser
{
[Key]
public int Id { get; set; }
public string UserName { get; set; }
public string UserLocation { get; set; }
public string UserStatus { get; set; }
//public IEnumerable<Glossary> Glossary { get; set; } //I used this for ViewBag
public List<SelectListItem> UserLocations { get; } = new List<SelectListItem>
{
according to the example my query should go here
};
}
Here is my controller:
public IActionResult Create()
{
// This is the ViewBag that worked with HTML helpers, but I'm trying to use tag-helpers.
/*IEnumerable<SelectListItem> LocationsList = _context.Glossary.Where(x => x.Category == 1).Select(x => new SelectListItem
{
Value = x.UniqueId.ToString(),
Text = x.DisplayText
});
ViewBag.LocationsList = LocationsList;
*/
return View();
}
All examples that found were hardcoded lists and nothing with getting it from the database. What is the proper way to get the data from the Glossary table through the view model with ViewBag? Any pointers are appreciated.
ALSO:
When using this example: Select Tag Helper in ASP.NET Core MVC
When I used
public SelectList Employees { set; get; }
I got error: InvalidOperationException: The entity type 'SelectListGroup' requires a primary key to be defined. If you intended to use a keyless entity type call 'HasNoKey()'.
Both of my tables have PK and adding [Key] to Glossary model didn't fix it.
If you'd like to retrieve data from db and populate a dropdown with retrieved data through a view model (or ViewBag), you can refer to following code snippet.
In AdminUser view model class, include these properties
public string Selected_Glossary { get; set; }
public List<SelectListItem> Glossary_List { get; set; }
In controller
public IActionResult Create(AdminUser model)
{
var adminuser_model = new AdminUser
{
UserName="test"
//for other properties
};
//retrieve data from Glossary table
var items = _context.Glossary.Where(x => x.Category == 1).Select(x => new SelectListItem
{
Value = x.UniqueId.ToString(),
Text = x.DisplayText
}).ToList();
//pass dropdown items through a view model
adminuser_model.Glossary_List = items;
////pass dropdown items through ViewBag
//ViewBag.Glossary_List = items;
return View(adminuser_model);
}
In view page
#model AdminUser
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<form asp-controller="Home" asp-action="Create" method="post">
<select asp-for="Selected_Glossary" asp-items="Model.Glossary_List"></select>
#*populate it through ViewBag*#
#*<select asp-for="Selected_Glossary" asp-items="ViewBag.Glossary_List"></select>*#
<input type="submit" value="Submit" />
</form>
Test Result

System.Web.Mvc.WebViewPage<T>.Model.get returned null

I am trying to create my first ASP.NET MVC application but since two days I cannot solve my problem.
I am using Entity Framework Code First approach. I want to create DropDownListFor but there is always this error:
System.NullReferenceException
System.Web.Mvc.WebViewPage.Model.get returned null.
My Model:
public class Animals
{
public int AnimalsId { get; set; }
public int ClientsId { get; set; }
public string Name { get; set; }
public int TypesId { get; set; }
public float Age { get; set; }
public float Weight { get; set; }
public virtual Types Types { get; set; }
public IEnumerable<Clients> ClientsList { get; set; }
public virtual ICollection<BookVisit> AnimalsVisits { get; set; }
}
My controller:
public ActionResult Create([Bind(Include = "AnimalsId, ClientsId, Name, TypesId, Age, Weight")] Animals animals)
{
var person = new List<Clients>
{
new Clients { ClientsId = 50, Name = "Timo", Surname = "Werner", Email = "timo.werner#gmail.com", Phone = 123123123 }
};
var animalsView = new Animals
{
ClientsList = person.Select(x => new Clients
{
ClientsId = x.ClientsId
})
};
if (ModelState.IsValid)
{
db.Animals.Add(animals);
db.SaveChanges();
return RedirectToAction("List", "Animal");
}
return View(animalsView);
}
My view (only #model and dropdown):
#model xyz.Models.Animals
#Html.DropDownListFor(model => model.ClientsId, new SelectList(Model.ClientsList, "ClientsId", "Name", "Surname", "Email", "Phone"))
Could you please take a look ?
From the comments, it looks like you are not passing a valid view model object to the view. Your view code is expecting a valid model passed to it and the helper methods are using different properties of that.
public ActionResult Create()
{
var clients = new List<Clients>
{
new Clients { ClientsId = 50, Name = "Timo" },
new Clients { ClientsId = 51, Name = "Microsoft" }
};
var vm = new Animals
{
ClientsList = clients
};
return View(vm);
}
Also your current code which calls the DropDownListFor is wrong. When you create a SelectList from a collection, you have to pass the dataValue field and dataText fields.
#model Animals
#Html.DropDownListFor(model => model.ClientsId,
new SelectList(Model.ClientsList, "ClientsId", "Name"))
This error may also be caused by trying to use a null model in razor view. In such case check if the model is null or not before using it as shown below:
#if (Model != null) {
<a onclick="get('#Url.Action("GetEmployee", "DemoController")', #Model.Id)" ></a>
}

substring one field on model and send to view

i have a model and i send substring one field on this model and return to a view for show in gridview
my model is:
public class News
{
public int ID { get; set; }
[MaxLength(300)]
public string Title { get; set; }
[DataType(DataType.MultilineText)]
[MaxLength]
public string Content { get; set; }
[ReadOnly(true)]
public DateTime Date { get; set; }
[Column("PictureID")]
public virtual Picture Picture { get; set; }
//public IList<Picture> PicID { get; set; }
[Column("NewsTypeID",Order=1)]
public virtual NewsType NewsType { get; set; }
public ICollection<Tag> Tags { get; set; }
public News()
{
Tags = new List<Tag>();
}
}
when i send this model by myController:
public ActionResult ShowNews()
{
var data = new DatabaseContext();
var news = data.newsInfo.ToList();
return View(news);
}
it is ok and show properly in gridview
but if send this model by this cod in controller:
public ActionResult ShowNews()
{
var data = new DatabaseContext();
var news = data.newsInfo.Select(x => new { Content = x.Content.Substring(0,200), x }).ToList();
return View(news);
}
show this Error:
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[<>f__AnonymousType02[System.String,NewsAgency.Models.News]]', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[NewsAgency.Models.News]'.
i have send substring one of the field
what is problem?
You have created list of anonymous objects in this statement:
data.newsInfo.Select(x => new { Content = x.Content.Substring(0,200), x }).ToList();
And you have send it as model to your view:
View(news);
But, in your view you have set model type as List<News>. So, the exception is throwned. Try to change your code as:
var news = data.newsInfo.AsEnumerable().Select(x => { x.Content = x.Content.Substring(0,200); return x; }).ToList();
If you want to send whole Content values along with substrings, then I recommend to use first way and get the substring of all item's Content with razor inside view.

mvc4 DropdownList does not set selected value

Hi I have a problem that drives me crazy. I have a dropdown list in one page of my project, which should act like on all the other dropdowns on all the other pages but it doesn't and I'm wondeing why.
Here you will see the code in the cshtml page. It's a normal dropdown:
<p>
Specify a organisation to search in
#Html.DropDownList("OrganisationList", new SelectList(ViewBag.OrganisationList, "ID", "Name", ViewBag.SelectedOrganisation))
</p>
In the controller I have a method to bind the dropdownlist and a method that calls the view:
private void BindAllOrganisations()
{
List<OrganisationModel> OrganisationList = new List<OrganisationModel> { new OrganisationModel { ID = null, Name = "Select" } };
foreach (var Organisation in DatabaseConnection.DataContextRead.GetTable<Organisation>())
{
OrganisationList.Add(new OrganisationModel { ID = Organisation.OrganisationId, Name = Organisation.Name });
}
ViewBag.OrganisationList = OrganisationList;
}
/**
* Loads the ManageUserView with all users from a specific organisation unit
**/
[AzaraAuthorization(RequiredRoles = new[] { RolesEnum.Admin })]
public ActionResult ManageUsersFromOrgUnit(int Id)
{
try
{
var orgUnit = organisationUnitManagement.GetSingleUnit(Id);
List<AzaraUser> AzaraUserList = azaraUserManagement.GetAllUserFromOrganisationUnit(orgUnit);
ViewBag.FromOrgUnits = Id;
BindAllOrganisations();
ViewBag.SelectedOrganisation = orgUnit.Organisation.OrganisationId;
return View("ManageUsers", AzaraUserList);
}
catch (BusinessObjectNotRetrievableByIdException exc)
{
ExceptionHandling.BusinessObjectNotRetrievableByIdExceptionOccured(exc, "ManageUsersFromOrgUnit(int Id)", "ManageUsersController");
return RedirectToAction("Index", "Home", new { Info = "A program error occured. The administrator get informed. Apologize the inconvenience." });
}
}
I can't find the problem. Also if I replace ViewBag.SelectedOrganisation on the Page with 1 (I know there is a model with value 1 in the database behind) it selects the value with null. Here is the used model for the list:
public class OrganisationModel
{
public int? ID { get; set; }
public string Name { get; set; }
}
Could there be a bug or what have I missed?

Categories