Telerik dropdownlist does not seem to bind to JSON - asp.net-mvc

I try to populate the dropdownlist from my database. When loading the view, the dropdownlist spinner appears to do something , then the spinner vanishes and the droplist is empty? Can someone propose a solution. Cheers.
QLine.cs
public partial class QLine
{
[Key]
public int lineId { get; set; }
public int networkId { get; set; }
[Required]
[StringLength(50)]
public string lineName { get; set; }
public virtual QNetwork QNetwork { get; set; }
}
LinesDroplistController.cs
public class LinesDroplistController : Controller
{
private KprModel db = new KprModel();
public JsonResult GetMLines()
{
var result = db.QLines.Where(abc => abc.networkId == 1);
return Json(result, JsonRequestBehavior.AllowGet);
}
}
myView.cshtml
#(Html.Kendo().DropDownList()
.Name("LineDropDownList")
.DataTextField("lineName")
.DataValueField("lineId")
.AutoBind(true)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetMLines", "LinesDroplist");
});
})
)

Please try this:
source.Read(read =>
{
read.Action("GetMLines", "LinesDroplist")
}).ServerFiltering(true);
When the serverFiltering is disabled, then the combobox will not make any additional requests to the server.

It worked when changing
var result = db.QLines.Where(abc => abc.networkId == 1);
to
var result = db.QLines.Where(abc => abc.networkId == 1).Select(x => new { x.lineName, x.lineId });

Related

Foreign key not appearing in View

Can anyone please assist,i have a model that contains a foreign key(ProductCategory).i am trying to call the values of the foreign key but they are not appearing in the view,when i place a breakpoint in the controller all fields appear successful in the raw results view but it seems they are not being passed to the view.
N.B i am using dev express to generate views
public class Product
{
public int Id { get; set; }
public int productCode { get; set; }
public double price { get; set; }
public int ProductCategoryId { get; set; }
public virtual ProductCategory ProductCategory { get; set; }
public Stock itemNo { get; set; }
}
[HttpGet]
public async Task<IActionResult> Get(DataSourceLoadOptions loadOptions) {
var product = _context.Product.Select(i => new {
i.Id,
i.productCode,
i.price,
i.ProductCategoryId,
i.ProductCategory.categoryDescr
});
return Json(await DataSourceLoader.LoadAsync(product, loadOptions));
}
#{
ViewData["Title"] = "Products";
}
<h2 class="content-block">Products</h2>
#(Html.DevExtreme().DataGrid<DevExtremeAspNetCoreApp1.Models.Product>()
.DataSource(ds => ds.Mvc()
.Controller("Products")
.LoadAction("Get")
.InsertAction("Post")
.UpdateAction("Put")
.DeleteAction("Delete")
.Key("Id")
)
.RemoteOperations(true)
.Columns(columns => {
columns.AddFor(m => m.productCode);
columns.AddFor(m => m.price);
columns.AddFor(m => m.ProductCategoryId);
columns.AddFor(m => m.ProductCategory.categoryDescr);
})
.Editing(e => e.Mode(GridEditMode.Popup)
.AllowAdding(true)
.AllowUpdating(true)
.AllowDeleting(true)
.Popup(p=>p
.Title("Product")
.ShowTitle(true)
.Width(500)
.Height(525)
)
)
.Export(e => e.Enabled(true))
)
Try this:
var product = _context.Product.Select(i => new {
i.Id,
i.productCode,
i.price,
i.ProductCategoryId,
ProductCategoryDesc=i.ProductCategory.categoryDescr
});
.....
columns.AddFor(m => m.ProductCategoryDesc);
turns i was passing an anonymous type,correct approach should be:
Controller
public async Task<IActionResult> Get(DataSourceLoadOptions loadOptions) {
var product = _context.Product.Select(i => new {
i.Id,
i.productCode,
i.price,
i.ProductCategoryId,
i.ProductCategory
});
View:
columns.AddFor(m => m.ProductCategory.Id);

How can one Fetch respected data from a table using TempData["Id"]

I've This Kendo UI Grid and I'm populating the grid with the values from a couple of tables
I've this GetBrands Method and I can get vales from other tables as you can see in the given method what I can't get is the vale from the TemData["CompanyId"]
how can I get CompanyName from This
public ActionResult GetBrands([DataSourceRequest] DataSourceRequest request)
{
var result= new DataSourceResult();
IQueryable<Brand> brands = null;
try
{
brands = db.Brands;
result = brands.AsQueryable()
.ToList()
.Select(b => new BrandListViewModels()
{
BrandName = b.BrandName,
ProductGroupCode = b.ProductGroupCode !=null? db.ProductGroups.FirstOrDefault(p => p.ProductGroupCode==b.ProductGroupCode).ProductGroupName:"N/A",
ProductSubGroupCode = b.ProductGroupCode != null ? db.ProductSubGroups.FirstOrDefault(p => p.ProductSubGroupCode == b.ProductSubGroupCode).ProductSubGroupName : "N/A",
// CompanyId = Convert.ToInt32(TempData["CompanyId"]) !=null? int.TryParse(db.Companies.FirstOrDefault(c=>c.Id==b.CompanyId).CompanyName, out id):"N/A"
}).OrderBy(b=>b.CompnayName)
.ToDataSourceResult(request);
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
//Temporary storing notification message
TempData["MESSAGE"] = js.Serialize(new { message = "Error has been occured while populating brands", type = "E" });
}
return Json(result,JsonRequestBehavior.AllowGet);
}
I tried To convert It and do lots of other stuff but its not working Its type is Int
Edit
Here is my BrandListViewModel
public class BrandListViewModels
{
public string ProductGroupCode { get; set; }
public string ProductSubGroupCode { get; set; }
public string BrandCode { get; set; }
public string BrandName { get; set; }
public int CompanyId { get; set; }
public string CompnayName { get; set; }
}
Here is my Grid
#(Html.Kendo().Grid(Model)
.Name("BrandGrid")
.Columns(columns =>
{
columns.Bound(c => c.CompanyId).Title("Company");
columns.Bound(c => c.BrandName).Title("Brand");
columns.Bound(c => c.ProductGroupCode).Title("Product Group");
columns.Bound(c => c.ProductSubGroupCode).Title("Product Sub Group");

Kendo grid image column

working on a MVC4 project, I'm trying to add a column to my kendo grid that displays an image.
<div id="datagrid">
#(Html.Kendo().Grid<SustIMS.Models.ConcessionModel>()
.Name("datagrid_Concessions")
.Columns(columns =>
{
columns.Bound(c => c.Code).Title(ViewBag.lblCode);
columns.Bound(c => c.Description).Title(ViewBag.lblDescription);
columns.Template(#<text>
<img src='#item.Image' />
</text>
).Title("Image");
})
I've tried that but no luck. Also tried:
columns.Template(#<text>
<img src='../../Images/pic.png' />
</text>
).Title("Image");
The images aren't shown, whether I define the image src in the controller or write it directly in the view.
I've checked both this and this question but the images aren't displayed.
Can anyone help?
EDIT
Here's the Concession Model:
public class ConcessionModel
{
public string Id { get; set; }
public string Code { get; set; }
public string Description { get; set; }
public string TrafficOpeningDate { get; set; }
public string CreationDate { get; set; }
public string CreationUser { get; set; }
public string Image { get; set; }
...
The Image property is a string that contains something like "C:\whatever\pic.png"
Try like this,
columns.Template(e => { }).ClientTemplate("<img src='../../Images/pic.png'/>").Width(140).Title("Image");
DEMO:
View
#(Html.Kendo().Grid<Category>().Name("people")
.DataSource(dataSource => dataSource
.Ajax()
.Model(model =>
{
model.Id(m => m.Id);
})
.Read(read => read.Action("GetCategory", "Category"))
)
.Columns(columns =>
{
columns.Bound(c => c.Id);
columns.Bound(c => c.ImageUrl).ClientTemplate("<img src='" + Url.Content("~/CategoryImage/") + "#=ImageUrl#' alt='#=Name #' Title='#=Name #' height='62' width='62'/>");
})
)
Model
public class Category
{
[ScaffoldColumn(false)]
public int Id { get; set; }
public string Name { get; set; }
[UIHint("FileUpload")]
[Required]
public string ImageUrl { get; set; }
public string FileName { get; set; }
internal static object ToDataSourceResult(Kendo.Mvc.UI.DataSourceRequest dsRequest)
{
throw new NotImplementedException();
}
}
Controller
public static List<Category> Category = new List<Category>();
private int _nextid = 4;
static CategoryController()
{
Category.Add(new Category { Id = 1, Name = "Desert", ImageUrl = "Desert.jpg" });
Category.Add(new Category { Id = 2, Name = "Hydrangeas", ImageUrl = "Hydrangeas.jpg" });
Category.Add(new Category { Id = 3, Name = "Tulips", ImageUrl = "Tulips.jpg" });
}
public ActionResult Index()
{
ViewData["Category"] = Category;
return View();
}
public ActionResult GetCategory([DataSourceRequest] DataSourceRequest dsRequest)
{
var result = Category.ToDataSourceResult(dsRequest);
return Json(result);
}

How to pass two vars from one controller into one view

I want this two methods pass to one view :
public IEnumerable<ProfitAndCostViewModel> getProfitSum()
{
var profBalance = db.Profits
.Where(x => x.IdUser.UserId == WebSecurity.CurrentUserId)
.GroupBy(x => x.IdUser.UserId)
.Select(x => new ProfitAndCostViewModel { ProfitSum = x.Sum(y => y.Value) })
.ToList();
return profBalance;
}
public IEnumerable<ProfitAndCostViewModel> getCostSum()
{
var costBalance = db.Costs
.Where(x => x.IdUser.UserId == WebSecurity.CurrentUserId)
.GroupBy(x => x.IdUser.UserId)
.Select(x => new ProfitAndCostViewModel { CostSum = x.Sum(y => y.Value) })
.ToList();
return costBalance;
}
in my ActionResult I Have this:
ProfitAndCostViewModel pcv = new ProfitAndCostViewModel();
pcv.ProfModel =getProfitSum();
pcv.CostModel =getCostSum();
return View(pcv);
And in ProfitAndCostViewModel code is this:
public double ProfitSum { get; set; }
public double CostSum { get; set; }
public double FinalBalance { get; set; }
public IEnumerable<ProfitAndCostViewModel> ProfModel { get; set; }
public IEnumerable<ProfitAndCostViewModel> CostModel { get; set; }
this is the error:
The model item passed into the dictionary is of type 'WHFM.ViewModels.ProfitAndCostViewModel', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[WHFM.ViewModels.ProfitAndCostViewModel]'.
Create a view model which has them both;
public class BigViewModel
{
public List<ProfitsModel> ProfModel { get; set; }
public List<CostsModel> CostModel { get; set; }
}
And controller
public ActionResult Index()
{
BigViewModel model = new BigViewModel();
model.costBalance = db.Costs...;
model.profBalance = db.Profits...;
return View(model)
}
You can wrap your parameters into a ViewModel or use a ViewBag

ASP.NET MVC post a dropdownlist

When I post via the click on "btSave", in the controller I receive the model. In the model, I see the value off all fields (I show here only "FirstName" but there are others). But the doropdownlist value are null all the time.
Do you have an idea why ?
Thanks,
//Dropfown content
public class LkpTypeCompany
{
public virtual int Id { get; set; }
public virtual int Code { get; set; }
public virtual string NL { get; set; }
public virtual string FR { get; set; }
public virtual string Value { get; set; }
}
//Model Definition
public class CustomerModel
{
public List<LkpTypeCompany> LkpTypeCompany { get; set; }
public Customer Customer { get; set; }
}
//Posting form
jQuery('#btGeneralSave').click(function (event) {
var jqxhr = $.post("Controller/Actio,", $("form").serialize(),
function (data) {
});
});
//HTML
#model eSIT.GC.WebUI.Models.CustomerModel
#using (Html.BeginForm())
{
#Html.TextBoxFor(m => m.Customer.FirstName, new { maxlength = 50 })
#Html.DropDownListFor( m => m.Customer.LkpTypeCompany, new SelectList(Model.LkpTypeCompany, "Code", "FR", Model.Customer.LkpTypeCompany.Code))
<input type="button" id="btSave" value="Save"/>
}
I see the overload that you were attempting to use but I have had good luch with using SelectListItem
Try
#Html.DropDownListFor( m => m.Customer.LkpTypeCompany,
new SelectList(Model.LkpTypeCompany
.Select(i => new SelectListItem
{
Text = i.Code,
Value = (*somecondition*) ? i.FR : i.NL,
Selected = i.Code == Model.Customer.LkpTypeCompany.Code
}));

Resources