I want to select a line of references to get the list of athor reference associat ,
this is the code of my view :
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Réf_OE)
</th>
<th>
#Html.DisplayNameFor(model => model.GENER_MOTORS)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Réf_OE)
</td>
<td>
#Html.DisplayFor(modelItem => item.GENER_MOTORS)
</td>
<td>
#Html.ActionLink("Select", "Select", new { Réf = item.Réf_OE })
</tr>
}
This the code of my select method :
[HttpGet]
public ActionResult Select(string Réf)
{
if (Réf != null)
{
var autres_ref = db.Autre_Références.Where(c => c.Réf_id == Réf).ToList();
ViewBag.autres_ref = autres_ref;
return RedirectToAction("Index", "Référence_Consctructeur");
}
else
{
return RedirectToAction("Create", "Référence_Consctructeur");
}
return RedirectToAction("Index", "Référence_Construscteur");
}
and i put the cursor on select it shows :
http://localhost:56616/R%C3%A9f%C3%A9rence_Consctructeur/Select/7700308756
I didn't understand why the paramter passed to select is null
please help.
The parameter name you are passing in your ActionLink should match with the parameter name in your action:
#Html.ActionLink("Select", "Select", new { Réf= item.Réf_OE })
Or change the parameter name of your action:
public ActionResult Select(string id){...}
Related
I have two tables. One is Booking and other is Course. Course can have many Bookings.
I want to count number of Bookings for each Course and pass that to ViewBag. So I want to count how many users applied for each Course.
This line counts total number o Bookings but I cant figure out how to do that for each Course.
ViewBag.Counter = db.Bookings.Count();
This line gets all the courses to my Index page.
IEnumerable<Course> courses = cr.GetCourses();
return View(courses.ToList());
And this is controller that is doing the work. I tried with 2 foreach loops but cant get it to work.
public ActionResult Index()
{
Booking booking = new Booking();
Course course = new Course();
List<Course> listCourses = new List<Course>();
List<Booking> bookings = new List<Booking>();
foreach (var item in listCourses)
{
int id = course.CourseId;
foreach (var item1 in bookings)
{
ViewBag.Counter = db.Bookings.Where(x => x.CourseId == id).Count();
}
}
IEnumerable<Course> courses = cr.GetCourses();
return View(courses.ToList());
}
I expect to get a number of users that applied for each course that is listed on my index page. I got no exceptions or errors and nothing shows up in my view. When I use ViewBag.Counter = db.Bookings.Count(); I get a total number of users that applied for all avaliable courses. Model on the view is Course model which is in relation with Booking with one to many relation.
This is the View for my ActionResult.
#model IEnumerable<Entities.Course>
#{
ViewBag.Title = "AlgebraSchoolApp";
}
<h2>Dobrodošli!</h2>
<p>
Da bi se prijavili na neki od naših tečajeva kliknite na link prijave:
<button>
#Html.ActionLink("Prijava","Create","Booking")
</button>
</p>
<h2> Svi tečajevi</h2>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.CourseName)
</th>
<th>
#Html.DisplayNameFor(model => model.Description)
</th>
<th>
#Html.DisplayName("Broj polaznika")
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.CourseName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#ViewBag.Counter
</td>
</tr>
}
</table>
<h2>Slobodni tečajevi</h2>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.CourseName)
</th>
<th>
#Html.DisplayNameFor(model => model.Description)
</th>
<th>
#Html.DisplayNameFor(model => model.Date)
</th>
</tr>
#foreach (var item in Model.Where(x => x.Full == false))
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.CourseName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.Date)
</td>
</tr>
}
</table>
The reason that ViewBag.Counter is showing the same result for all courses is because it is being overwritten each time with ViewBag.Counter = db.Bookings.Where(x => x.CourseId == id).Count();.
If i have understood your issue this can be fixed by creating a new view model to store the required information for a course and return this to your view. EG:
public class CourseViewModel
{
public string CourseName { get; set; }
public string Description { get; set; }
//etc
public int BookingCount { get; set; }
}
Controller:
public ActionResult Index()
{
var courses = cr.GetCourses();
var courseViewModels= new List<CourseViewModel>();
foreach (var course in courses )
{
var bookingCount = db.Bookings.Where(x => x.CourseId == course.CourseId).Count();
courseViewModels.Add(new CourseViewModel{
CourseName = course.CourseName, //Add all the vm properties
BookingCount = bookingCount
});
}
return View(courseViewModels);
}
In the view:
#model IEnumerable<CourseViewModel>
#/*...*/
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.CourseName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.BookingCount )
</td>
</tr>
}
I'm trying to create a simple view (paging, sorting and filtering).
The method I have that does that looks something like this:
public IEnumerable<VehicleMakeEntity> GetMake(int index, int count,
Expression<Func<VehicleMakeEntity, int>> orderLambda)
{
var data = _makeRepository.SelectListMake(index, count, orderLambda).AsQueryable();
return data;
}
You see it call another method from a repository, which looks the same
private readonly IQueryable<VehicleMakeEntity> _source;
public MakeRepository(ProjectDbContext context)
{
this.context = context;
_source = this.context.VehicleMake;
}
public IEnumerable<VehicleMakeEntity> SelectListMake(int index, int count,
Expression<Func<VehicleMakeEntity, int>> orderLambda)
{
return _source.Skip(index * count).Take(count).OrderBy(orderLambda);
}
In my controller I call the method
public IActionResult Make()
{
var data = _vehicleService.GetMake(1, 10, (p => p.Id));
return View(data);
}
And it returns some data I do not know how to work with as seen here
I also generated a View based on that controller method, a basic List View which you can see here
#model IEnumerable<Data.Entities.VehicleMakeEntity>
#using NonFactors.Mvc.Grid;
#{
ViewData["Title"] = "Make View";
}
<h2>Make View</h2>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Id)
</th>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Abrv)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Abrv)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</tbody>
But nothing is displaying on the site. Am I supposed to do something with the returned data? What am I doing wrong? I checked if the entities aren't getting the information from the database, they are.
Can you check with below code.
public IActionResult Make()
{
var data = _vehicleService.GetMake(1, 10, (p => p.Id)).ToList();
return View(data);
}
Also try to remove AsQueryable()
public IEnumerable<VehicleMakeEntity> GetMake(int index, int count, Expression<Func<VehicleMakeEntity, int>> orderLambda)
{
return _makeRepository.SelectListMake(index, count, orderLambda);
}
I have been reviewing possible ways to return a View's #model information which is of type IEnumerable back to the controller, so that if I sort/filter on a query from database, I can refine the return each iteration without restarting with a fresh full list being returned. All the ways show you need to POST back based on model[index] which works if you are inside a for loop. But I am working with sending the collection back from an #HTML.ActionLink within a table's header section, so there is no possible indexing available.
My WebAPI setup is based on this where they show how to sort and filter. I am trying to make it a little more complex in that after I filter a list based on my original DB query, I will then be able to sort (from a clickable-actionLink on a table's header column) from that filtered list; where as currently it would just sort from a fresh complete list.
The only way I can think of to do this is pass back (by a POST) to the controller the updated list of the customClass.
#Html.ActionLink("Name", "Index", new { orderBy = ViewBag.sortByName,
companyListIds = Model.???? })
A better option (based on comments from Tacud) which would require a smaller POST URL would be by returning a list of the id properties only which can then be applied to a query. But its still a list and still needs to be sent back without an index from and ActionLink. This will help keep track and allow me to continue drilling down to a smaller and smaller list.
Below is parts of my model class, the index Action from the controller, and the index view.
Model namespace:
public class Company
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
}
Controller Namespace:
public async Task<IActionResult> Index(ICollection<int> prev, string orderBy , string searchCategory ="", string searchString = "")
{
List<string> Categories = new List<string>() { "Name", "City", "State", "Zip", "Contact Person" };
ViewBag.searchCategory = new SelectList(Categories);
ViewBag.sortByName = orderBy == null ? "name" : orderBy == "name" ? "namedesc" : "name";
ViewBag.sortByCity = orderBy == "city" ? "citydesc" : "city";
ViewBag.sortByState = orderBy == "state" ? "statedesc" : "state";
ViewBag.companyIndex = companyList.Count==0 ? await _context.Company.ToListAsync() : companyList ;
List<Company> resultSet = new List<Company>(ViewBag.companyIndex);
if (!String.IsNullOrEmpty(searchCategory) && !String.IsNullOrEmpty(searchString))
{
switch (searchCategory)
{
.....
}
}
switch (orderBy)
{
....
}
return View(resultSet);
}
View namespace:
#model IEnumerable<Laier_It.Models.Company> <p>
#using (Html.BeginForm() {
<p>
Search By: #Html.DropDownList("SearchCategory", "")
Search For: #Html.TextBox("SearchString")
<input type="submit" value="Filter" />
</p> }
<table class="table ">
<thead>
<tr>
<th>
#Html.ActionLink("Name", "Index", new { orderBy = ViewBag.sortByName, companyList = Model })
</th>
<th>
#Html.DisplayNameFor(model => model.Address)
</th>
<th>
#Html.ActionLink("City", "Index", new { orderBy = ViewBag.sortByCity, companyList = Model })
</th>
<th>
#Html.ActionLink("State", "Index", new { orderBy = ViewBag.sortByState, companyList = Model })
</th> </tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Address)
</td>
<td>
#Html.DisplayFor(modelItem => item.City)
</td>
<td>
#Html.DisplayFor(modelItem => item.State)
</td> </tr>
}
</tbody>
</table>
To first obtain the list of Id's that I want to post back to the controller of the current rendition showing within the WebAPI view page I used #Model.Select(x => x.Id)
My controller index method was only changed by this
var resultSet = prev.Count == 0 ? await _context.Company.ToListAsync() :
await _context.Company.Where(x => prev.Contains(x.Id)).ToListAsync();
And my View looks like this:
#model IEnumerable<Laier_It.Models.Company>
#using (Html.BeginForm() )
{
<p>
Search By: #Html.DropDownList("SearchCategory", "")
Search For: #Html.TextBox("SearchString")
<input type="submit" value="Filter" />
</p>
}
<table class="table ">
<thead>
<tr>
<th>
#Html.ActionLink("Name", "Index", new { orderBy = ViewBag.sortByName, prev = #Model.Select(x => x.Id) } )
</th>
<th>
#Html.DisplayNameFor(model => model.Address)
</th>
<th>
#Html.ActionLink("City", "Index", new { orderBy = ViewBag.sortByCity, prev = #Model.Select(x => x.Id) } )
</th>
<th>
#Html.ActionLink("State", "Index", new { orderBy = ViewBag.sortByState, prev = #Model.Select(x => x.Id) } )
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Address)
</td>
<td>
#Html.DisplayFor(modelItem => item.City)
</td>
<td>
#Html.DisplayFor(modelItem => item.State)
</td>
</tr>
}
</tbody>
</table>
I'm trying to submit only these rows which is checked. I'm using this jquery plungin and my table looks same as is in link
#model IEnumerable<BillBox.ACD_UNI_STUDENTS>
<table class="table tblSelect">
<tr>
<th>
<input type="checkbox" id="checkall" title="Select all" />
</th>
<th>
#Html.DisplayNameFor(model => model.FIRST_NAME)
</th>
<th>
#Html.DisplayNameFor(model => model.LAST_NAME)
</th>
<th>
#Html.DisplayNameFor(model => model.PERSONAL_NUMBER)
</th>
<th>
#Html.DisplayNameFor(model => model.ACD_UNI_DEGREES.DEGREE)
</th>
<th>
#Html.DisplayNameFor(model => model.ACD_UNI_FACULTIES.FACULTY)
</th>
<th>
#Html.DisplayNameFor(model => model.ACD_UNI_SEMESTERS.SEMESTER)
</th>
<th>
#Html.DisplayNameFor(model => model.ACD_UNI_SPECIALIZATIONS.SPECIALIZATION)
</th>
<th>
#Html.DisplayNameFor(model => model.COR_PAYER_STATUS.NAME)
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
<input type="checkbox"/>
</td>
<td>
#Html.DisplayFor(modelItem => item.FIRST_NAME)
</td>
<td>
#Html.DisplayFor(modelItem => item.LAST_NAME)
</td>
<td>
#Html.DisplayFor(modelItem => item.PERSONAL_NUMBER)
</td>
<td>
#Html.DisplayFor(modelItem => item.ACD_UNI_FACULTIES.FACULTY)
</td>
<td>
#Html.DisplayFor(modelItem => item.ACD_UNI_SEMESTERS.SEMESTER)
</td>
<td>
#Html.DisplayFor(modelItem => item.ACD_UNI_SEMESTERS.SEMESTER)
</td>
<td>
#Html.DisplayFor(modelItem => item.ACD_UNI_SPECIALIZATIONS.SPECIALIZATION)
</td>
<td>
#Html.DisplayFor(modelItem => item.COR_PAYER_STATUS.NAME)
</td>
</tr>
}
</table>
Now I have a question. How can I retrieve only these rows which checkbox is checked?
that's my controller
public PartialViewResult AllStudent()
{
var students = (from q in db.ACD_UNI_STUDENTS
select q).ToList();
return PartialView(students);
}
there are many rows (from db) so I can't do it with formcollection. I can't retrieve their names
You may submit the selected ids as IEnumerable and then filter them in your controller! Here is an example
<form action="url" method="post">
...
#foreach (var item in Model)
{
<tr>
<td>
<input type="checkbox" name="Objs[]" id="Objs[]" value="#item.UNIQUE_ID"/>
</td>
<td>
#Html.DisplayFor(modelItem => item.FIRST_NAME)
</td>
</tr>
}...
</form>
and your controller
[HttpPost]
public PartialViewResult AllStudent(IEnumerable<long> Objs)
{
var students = (from q in db.ACD_UNI_STUDENTS
where Objs.Contains(q.UNIQUE_ID)
select q).ToList();
return PartialView(students);
}
...
I'd suggest not to use the Database Model for the View directly. You should have a Model to bind to the Rows, which might look like:
public class StudentRowViewModel
{
public bool IsChecked { get; set; }
public int StudentId { get; set; }
// ... More columns, whatever you want to display
public string Name { get; set; }
}
When populating the View, you select StudentRowViewModels like this:
db.ACD_UNI_STUDENTS.Select(x => new StudentRowViewModel { StudentId = x.UNIQUE_ID, Name = ... });
Or whatever applies to your DataBase Model.
In your View, your Checkbox will also Bind to the Model:
#Html.CheckboxFor(x => x.IsChecked)
Finally, when the Form is submitted, you can select only the checked Items:
public ActionResult AllStudents(IEnumerable<StudentRowViewModel> model)
{
var checked = model.Where(x => x.IsChecked).Select(x => x.StudentId).ToList();
var items = db.ACD_UNI_STUDENTS.Where(x => checked.Contains(x.UNIQUE_ID));
}
You get the Idea?
First put a class and value attribute in your checkbox :
<input type="checkbox" class="myCheckBox" value="#item.PERSONAL_NUMBER" />
Then i advise you to use a JQuery script to detect which checkbox are checked :
I suppose that you have a button to do another action :
$(document).ready(function () {
$('#myButton').click(function() {
var id = '';
$('.myCheckBox:checked').each(function (e) {
id += $(this).val() + ';'
}
var url = '/ControllerName/ActionResultName';
$.ajax({
url:url,
cache: false,
type: 'POST',
data: {
Id: id
},
succes: function(data){
$('.myCheckBox').attr('checked',false);
location.reload();
}
})
}
});
After that you can get in your controller all the personnal numbers in your controller :
put a string parameter 'id' to your actionresult.
id.TrimEnd(';')
Problem:
I have List of Categories with SubCategories, so when i click on SubCategory item it redirect me to List of Entries. There along the list it has Create ActionLink. So the problem is passing the SubCategoryId when I click SubCategoryItem for the Create ActionLink. Without the CreateActionLink it lists the entries but with it, it gives an error in the index view:
Object reference not set to an instance of an object.
Line 6:
Line 7: <p>
Line 8: #Html.ActionLink("Create New", "Create", new { subCategoryId = #Model.SubCategoryId})
Line 9: </p>
Line 10:
I understand that i am passing null reference and the question is how to avoid that?
Here is my code:
Controller:
public class EntryController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult EntryList(int subCategoryId)
{
var entries = EntryDAL.GetEntries(subCategoryId);
return View("_EntryList",entries);
}
public ActionResult Create(int subCategoryId)
{
var model = new Entry();
model.SubCategoryId = subCategoryId;
return View(model);
}
[HttpPost]
public ActionResult Create(Entry entry)
{
try
{
if (ModelState.IsValid)
{
var add = EntryDAL.Add(entry);
return RedirectToAction("Index");
}
return View(entry);
}
catch (Exception)
{
return View();
}
}
}
IndexView:
#model PasswordCloud.Domain.Models.SubCategory
#{
ViewBag.Title = "Index";
}
<p>
#Html.ActionLink("Create New", "Create", new { subCategoryId = #Model.SubCategoryId })
</p>
#{Html.RenderPartial("_EntryList",Model.EntryList);}
PartialView:
#model IEnumerable<PasswordCloud.Domain.Models.Entry>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.Title)
</th>
<th>
#Html.DisplayNameFor(model => model.Username)
</th>
<th>
#Html.DisplayNameFor(model => model.Password)
</th>
<th>
#Html.DisplayNameFor(model => model.Url)
</th>
<th>
#Html.DisplayNameFor(model => model.Description)
</th>
<th>
#Html.DisplayNameFor(model => model.SubCategoryId)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.Username)
</td>
<td>
#Html.DisplayFor(modelItem => item.Password)
</td>
<td>
#Html.DisplayFor(modelItem => item.Url)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.SubCategoryId)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
#Html.ActionLink("Details", "Details", new { id=item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
SubCategoryListItem View:
#model IEnumerable<PasswordCloud.Domain.Models.SubCategory>
#foreach (var item in Model) {
#Html.ActionLink(item.Name,"Index","Entry", new { subCategoryId = item.SubCategoryId }, null)
}
In your Index action you never create a model and pass it to the view. So when it gets to your line where you make the action link where you use new { subCategoryId = #Model.SubCategoryId} your model is null. Thus you get a null ref exception. To fix it you need to do something like this.
public ActionResult Index()
{
var model = ...
return View(model);
}