I'm using Kendo grid (MVC) to create list of radio stations. The grid code is as follows:
#(Html.Kendo().Grid<ReportStationViewModel>(Model.ReportStations)
.Name("ReportStations")
.Columns(columns =>
{
columns.Select();
columns.Bound(p => p.Station.StationFieldId).ClientTemplate("#= Station.StationFieldId #" + "<input type='hidden' name='ReportStations[#= index(data)#].Station.StationFieldId' value='#= Station.StationFieldId #' />")
.Title("Station Id").Filterable(f => f.Multi(true).Search(true));
columns.Bound(p => p.Station.StationName).ClientTemplate("#= Station.StationName #" + "<input type='hidden' name='ReportStations[#= index(data)#].Station.StationName' value='#= Station.StationName #' />")
.Title("Name").Filterable(f => f.Multi(true).Search(true));
columns.Bound(p => p.Station.StationId).Hidden().ClientTemplate("#= StationId #" + "<input type='hidden' name='ReportStations[#= index(data)#].Station.StationId' value='#= Station.StationId #' />");
columns.Bound(p => p.ReportStationId).Hidden().ClientTemplate("#= ReportStationId #" + "<input type='hidden' name='ReportStations[#= index(data)#].ReportStationId' value='#= ReportStationId #' />");
columns.Bound(p => p.ReportId).Hidden().ClientTemplate("#= ReportId #" + "<input type='hidden' name='ReportStations[#= index(data)#].ReportId' value='#= ReportId #' />");
columns.Bound(p => p.StationId).Hidden().ClientTemplate("#= StationId #" + "<input type='hidden' name='ReportStations[#= index(data)#].StationId' value='#= StationId #' />");
})
.Editable(e => e.Mode(GridEditMode.PopUp))
.Filterable()
.Selectable()
.Mobile()
.Events(e => e.Change("onChange").DataBound("onDataBind"))
.DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(false)
.Events(events => events.Error("error_handler").Sync("sync_handler"))
.Model(model =>
{
model.Id(s => s.ReportStationId);
model.Field(f => f.ReportStationId).Editable(false);
})
.Read(read => read.Action("GetAllRead", "ReportStations").Data("onData"))
.Destroy(destroy => destroy.Action("RemoveStation", "ReportStations"))
))
The ViewModel is as follows:
public class ReportViewModel{
public int ReportId { get; set; }
public string ReportName { get; set; }
public virtual Organization Organization { get; set; }
public List<ReportStationViewModel> ReportStations { get; set; }}
public class ReportStationViewModel{
public int ReportStationId { get; set; }
public int ReportId { get; set; }
public int StationId { get; set; }
public virtual StationViewModel Station { get; set; }
public ICollection<ReportStationPlatformViewModel> ReportStationPlatforms { get; set; }}
it populates grid correctly and i can see all the information I need. But when I try to select a row it doesn't check it. and it is not throwing any JS error.
any idea what am I doing wrong here?
Try removing the .Selectable() of your grid. For some reason it doesn't work alongside the checkbox selection.
Related
I have the following form:
#using (Html.BeginForm())
{
#Html.LabelFor(a => a.SomeText)
#Html.TextBoxFor(a => a.SomeText, new { #class = "form-control" })
#Html.ValidationMessageFor(a => a.SomeText)
<select name="ListOne" id="ListOne">
#foreach (var item in Model.ListOne)
{
<option value="#item.Id">#item.Name</option>
}
</select>
#Html.DropDownListFor(a => a.ListTwo, listTwo, null);
<input type="submit" value="Do Stuff" class="btn-primary"
asp-controller="My" asp-action="DoStuff"/>
. . .
}
On the server side, I have a simple controller method:
public async Task<IActionResult> DoStuff(MyViewModel myViewModel)
{
// ...
}
A breakpoint here shows that neither select list gets passed through, despite them both being visible in the HTML.
The VM looks like this:
public class MyViewModel
{
public string? SomeText { get; set; }
public SelectList? ListOne { get; set; } = new(new List<SelectListItem>());
public SelectList? ListTwo { get; set; } = new(new List<SelectListItem>());
}
ListOne and ListTwo are both null.
Please - could someone tell me why?
In my Razor web app, I've tried to get a list of users and their roles the following ways:
_userManager.GetUsersInRoleAsync(role).Result;
_dbContext.Users.Include(u => u.UserRoles).ThenInclude(u => u.Role);
_userManager.Users.Include(u => u.UserRoles).ThenInclude(ur => ur.Role).ToList();
And UserRoles is always null. Any idea what I'm doing wrong?
Here is my Startup:
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddDefaultUI()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();
Here is my model:
public class ApplicationUser : IdentityUser
{
public virtual ICollection<ApplicationUserRole> UserRoles { get; set; }
}
public class ApplicationRole : IdentityRole
{
public virtual ICollection<ApplicationUserRole> UserRoles { get; set; }
}
public class ApplicationUserRole : IdentityUserRole<string>
{
public virtual ApplicationUser User { get; set; }
public virtual ApplicationRole Role { get; set; }
}
Here is my OnModelCreating:
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<ApplicationUser>(au =>
{
au.HasMany(e => e.UserRoles).WithOne(e => e.User).HasForeignKey(ur => ur.UserId).IsRequired();
});
builder.Entity<ApplicationRole>(ar =>
{
ar.HasMany(e => e.UserRoles).WithOne(e => e.Role).HasForeignKey(ur => ur.RoleId).IsRequired();
});
builder.Entity<ApplicationUserRole>(aur =>
{
aur.HasOne(ur => ur.Role).WithMany(r => r.UserRoles).HasForeignKey(ur => ur.RoleId).IsRequired();
aur.HasOne(ur => ur.User).WithMany(r => r.UserRoles).HasForeignKey(ur => ur.UserId).IsRequired();
});
}
I have some DB models:
public class SomeEntity
{
[Key]
public int Id { get; set; }
public Schedule Schedule { get; set; }
public ICollection<Address> Addresses { get; set; }
public ICollection<Phone> Phones { get; set; }
public ICollection<Email> Emails { get; set; }
}
and
public class Schedule
{
[Key]
public int id { get; set; }
public ICollection<TimeRange> Monday { get; set; }
public ICollection<TimeRange> Tuesday { get; set; }
public ICollection<TimeRange> Wednesday { get; set; }
public ICollection<TimeRange> Thursday { get; set; }
public ICollection<TimeRange> Friday { get; set; }
public ICollection<TimeRange> Saturday { get; set; }
public ICollection<TimeRange> Sunday { get; set; }
}
And when I run:
var entity = _dbContext.SomeEntity
.Include(p => p.Addresses)
.Include(p => p.Emails)
.Include(p => p.Phones)
.Include(p => p.Schedule)
.ThenInclude(s => s.Monday)
.Include(p => p.Schedule)
.ThenInclude(s => s.Tuesday)
.Include(p => p.Schedule)
.ThenInclude(s => s.Wednesday)
.Include(p => p.Schedule)
.ThenInclude(s => s.Thursday)
.Include(p => p.Schedule)
.ThenInclude(s => s.Friday)
.Include(p => p.Schedule)
.ThenInclude(s => s.Saturday)
.Include(p => p.Schedule)
.ThenInclude(s => s.Sunday)
return entity;
It tooks a very long time to execute. How can I fix this?
You have way too many includes. There is currently no option to optimize it directly (include with filters will be in next version of ef core 2.1). If you really need all that data, you should use rawquery.
I just can`t find out what is wrong. I am trying no to allow setting null values to field, when user tries to do it, it must show message "*", and wait for him to set values, but it doesnot work and null values are successfully sent to an action.
Model :
public class CompanyMainInfoModel
{
public int CompanyId { get; set; }
[Required(ErrorMessage = "*")]
[Display(Name = "company_name", ResourceType = typeof(Localization))]
public string CompanyName { get; set; }
[Required(ErrorMessage = "*")]
[Display(Name = "company_address", ResourceType = typeof(Localization))]
public string CompanyAddress { get; set; }
[Required(ErrorMessage = "*")]
[Display(Name = "company_director", ResourceType = typeof(Localization))]
public string CompanyDirector { get; set; }
[Required(ErrorMessage = "*")]
[Display(Name = "company_phone", ResourceType = typeof(Localization))]
public string CompanyTelephoneNumber { get; set; }
}
Markup :
#model BTGHRM.Models.CompanyMainInfoModel
#{
Layout = "~/Views/Shared/_EmployeeMain.cshtml";
}
<head>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery-ui.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
</head>
<body>
<span class="content_h4">#Resources.Localization.company_info</span>
<br />
<br />
<div id="FormContainer">
#Html.Partial("Partial/_CompanyInfo", Model)
</div>
</body>
Partial Markup:
#model BTGHRM.Models.CompanyMainInfoModel
#using (Html.BeginForm("CompanyInfo", "Administration"))
{
<table>
<tr>
<td>#Html.LabelFor(m => m.CompanyName)</td>
<td>#Html.TextBoxFor(m => m.CompanyName)</td>
<td>#Html.ValidationMessageFor(m => m.CompanyName, "" , new { #class="text-danger"})</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.CompanyAddress)</td>
<td>#Html.TextBoxFor(m => m.CompanyAddress)</td>
<td>#Html.ValidationMessageFor(m => m.CompanyAddress, "", new { #class = "text-danger" })</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.CompanyDirector)</td>
<td>#Html.TextBoxFor(m => m.CompanyDirector)</td>
<td>#Html.ValidationMessageFor(m => m.CompanyDirector, "", new { #class = "text-danger" })</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.CompanyTelephoneNumber)</td>
<td>#Html.TextBoxFor(m => m.CompanyTelephoneNumber)</td>
<td>#Html.ValidationMessageFor(m => m.CompanyTelephoneNumber, "", new { #class = "text-danger" })</td>
</tr>
</table>
<input style="width:78px" type="submit" value=#Resources.Localization.save />
}
And despite [Required] it still allows me to set null values to any field.
What is wrong with my code?
You have to have unobtrusive scripts enabled in web config
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
Then you need to add
jquery
jquery.validate.js
jquery.validate.unobtrusive.js
You need to add "jquery.validate.js" and "jquery.validate.unobtrusive.js" in your View. Validation needs the above two files along with "Jquery.js". Hope this helps.
I don't know why it don't save the AddressBookId form a select in my database
public class CreditCard
{
public int Id { get; set; }
[Display (Name="Customer")]
public int CustomerID { get; set; }
[Display(Name = "Billing Address")]
public int AddressBooKId { get; set; }
public virtual Customer Customer { get; set; }
}
Controller:
public ActionResult Create()
{
ViewBag.CustomerID = new SelectList(db.Customers, "Id", "FullName");
ViewBag.CCTypeId = new SelectList(db.CreditCardTypes, "Id", "CCName");
return View();
}
public JsonResult AddList(int Id)
{
var add = from a in db.AddressBooks
where a.CustomerId== Id
select a;
return Json(new SelectList(add.ToArray(), "AddressBookId", "Address"), JsonRequestBehavior.AllowGet);
}
public IList<AddressBook> Getadd(int CustomeId)
{
return db.AddressBooks.Where(m => m.CustomerId== CustomeId).ToList();}
Mi view
<div class="form-group">
#Html.LabelFor(model => model.AddressBooKId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<select id="AddressBooKId" name="AddressBooKId" class="form-control"> </select><br />
#Html.ValidationMessageFor(model => model.AddressBooKId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
Json
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/jscript">
$(function () {
$('#AddressBooKId').html(null)
$('#CustomerID').change(function () {
$.getJSON('/CreditCards/AddList/' + $('#CustomerID').val(), function (data) {
var items = '<option>Select a Address</option>';
$.each(data, function (i, add) {
items += "<option value='" + add.Value + "'>" + add.Text + "</option>"; });
$('#AddressBooKId').html(items);
}); }); });
</script>
Because your Dropdown is not bound with Model. You are creating it as independent control.
<select id="AddressBooKId" name="AddressBooKId" class="form-control"> </select>
Change the list Id and name to "AddressBookList". Create hidden field to keep the AddressBookId using model.
#Html.HiddenFor(m => m.AddressBooKId);
Change your JS code to update the new dropdown name.
Create a new change event handler for AddressBookList and set the value of HiddenField.
$('#AddressBookList').change(function () {
$('#AddressBooKId').val($('#AddressBookList').val());
}
Now when form will be submitted the Model property AddressBookId will have the selected value.