How can one Fetch respected data from a table using TempData["Id"] - asp.net-mvc

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");

Related

MVC Drop Down List issue : There is no Viewdata item of type 'IEnumerable<SelectListItem>' that has the key

Contoller:
public async Task<ActionResult> GetAssiginee()
{
var AssigineeList = await this.handsService.GetTeamTask();
var content = from p in AssigineeList.Data
orderby p.claimid
select new { p.claimid, p.Assiginee};
var x = content.ToList().Select(c => new List<SelectListItem>
{
new SelectListItem { Text = c.claimid, Value = c.Assiginee},
}).ToList();
ViewBag.FirstName = x;
return View();
}
Model :
public class ClaimDetails
{
public int Assigineeid { get; set; }
public List<ClaimDetails> AssigineeList { get; set; }
public int ID { get; set; }
public string claimid { get; set; }
public string contactID { get; set; }
public string Creator { get; set; }
public string Description { get; set; }
public string status { get; set; }
public string StartDate { get; set; }
public string EndDate { get; set; }
public string ForensicDueDate { get; set; }
public string ForensicDueTime { get; set; }
public string PatientFirstName { get; set; }
public string PatientLastName { get; set; }
public string Client { get; set; }
public string ProviderName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string PreScreen { get; set; }
public string Priority { get; set; }
public string Edit { get; set; }
public string Comment { get; set; }
public string Assiginee
{
get
{
return string.Format("{0} {1}", this.FirstName ?? string.Empty, this.LastName ?? string.Empty).Trim();
}
set
{
}
}
public string Patient
{
get
{
return string.Format("{0} {1}", this.PatientFirstName ?? string.Empty, this.PatientLastName ?? string.Empty).Trim();
}
}
}
}
View DropDown List:
I try for those DropDownList ,but showing Error Message
#Html.DropDownListFor(m => m.FirstName,
new SelectList(ViewBag.FirstName as IEnumerable<SelectListItem> Enumerable.Empty<SelectListItem>(), "claimid", "FirstName"),
"Select Assiginee",
new { #style = "width: 180px;height:30px;", id = "ddlAssiginee", #class = "form-control" })
#Html.DropDownList("dropdownCountry", new SelectList(string.Empty, "claimid", "FirstName"), "Select Assiginee", new { #class = "form-control", #style = "width:250px;" })
#Html.DropDownListFor(model => model.ID, ViewBag.FirstName as IEnumerable<SelectListItem>)
#Html.DropDownList("ddldepartmentlist", ViewBag.FirstName as IEnumerable<SelectListItem>)
JavsScript Function:
<script language="javascript" type="text/javascript">
$(function () {
$.ajax({
type: "GET",
url: "/TeamTaskScreen/GetAssiginee",
datatype: "Json",
success: function (data) {
$.each(data, function (index, value) {
$('#ddldepartmentlist').append('<option value="' + value.claimid + '">' + value.FirstName + '</option>');
debugger;
});
}
});
});
</script>
values are coming in Contoller but I Got Error Message in DropDownList
There is no Viewdata item of type IEnumerable<SelectListItem> that has the key
Please help any one.
ViewBag works when you set it in a GET action and try to access it in the view returned by that action method. But in your code, you are making an ajax call to get the data for the dropdown. Your ajax call's success method is expecting an array of items each with claimId and FirstName, but currently you server method is trying to return a view result!
Your view is expecting the a ViewBag item with name FirstName which has the collection of SelectListItems to render the SELECT element options. That means you need to set this ViewBag item in the GET Action method which returns this view, not in some other action method called by an ajax call.
So update your GET action to set this data.
public ActionResult Create()
{
// your existing code to load content collection here
var x = content.Select(c => new List<SelectListItem>
{
Text = c.claimid,
Value = c.Assiginee},
}).ToList();
ViewBag.FirstName = x;
return View();
}
Another option is to simply use the Ajax method. For this, you may return the data in JSON format from your GetAssiginee method.
public async Task<ActionResult> GetAssiginee()
{
var AssigineeList = await this.handsService.GetTeamTask();
var content = from p in AssigineeList.Data
orderby p.claimid
select new { p.claimid, p.Assiginee};
var x = content.Select(c => new claimid= c.claimid,
FirstName= c.Assiginee}).ToList();
return Json(x,JsonRequestBehavior.AllowGet);
}
The above code will return a json array like below
[
{ "claimid":"1","FirstName":"Some Name"},
{ "claimid":"2","FirstName":"Some Other Name"}
]
and your current js code will be able to loop through the array and append options to the select element.
Now since you are populating the data via ajax, no need to use VieBag. Simple replace
#Html.DropDownList("ddldepartmentlist", ViewBag.FirstName as IEnumerable<SelectListItem>)
with
<SELECT name="ddldepartmentlist"></SELECT>

Telerik dropdownlist does not seem to bind to JSON

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 });

Data not showing in Kendo MVC Grid

I've used Kendo Grid for showing data.It seems data is passed correctly because when I tracing my code in run time, I see there are some data in result but Kendo Grid couldn't show the data.
How can I solve this problem?
EDIT DESCRIPTION:
I found cause of problem but I cannot solve it.
If I remove this line in my ViewModel in QueryBuilder() method,
Tags = article.ArticleTags.Where(c => c.ArticleId == article.Id).Select(b => b.Tag).Distinct().ToList()
Grid show data but I need values of Tags. why this line of code has been caused the problem?
Tag model:
public class Tag : Entity, ITag
{
public Tag()
{
}
public virtual string Title { get; set; }
public virtual string Description { get; set; }
public virtual bool? IsActive { get; set; }
[Range(1, 4)]
public virtual int Size { get; set; }
public virtual ISet<ArticleTag> ArticleTags { get; set; }
public virtual ISet<ProjectTag> ProjectTags { get; set; }
}
my grid:
#using Jahan.Blog.Web.Mvc.HtmlHelpers
#using Kendo.Mvc.UI
#using Kendo.Mvc.UI.Fluent
#model IEnumerable<Jahan.Blog.ViewModel.ArticleViewModel>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<div style="width: 100%;">
#(Html.Kendo().Grid<Jahan.Blog.ViewModel.ArticleViewModel>()
.Name("ArticleAdmin").Navigatable()
.Resizable(c => c.Columns(true))
.HtmlAttributes(new { #class = "cursorLink", #style = "width: 1000px;height:auto;overflow: scroll;" })
.Columns(columns =>
{
columns.Bound(p => p.Id).Width(100);
columns.Bound(p => p.Title).Width(200);
columns.Command(command => command.Destroy()).Width(170);
})
.ToolBar(toolbar =>
{
toolbar.Create();
toolbar.Save();
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Pageable()
.Navigatable()
.Sortable()
.Scrollable()
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.PageSize(10)
.ServerOperation(false)
.Events(events => events.Error("error_handler"))
.Model(model => model.Id(p => p.Id))
.Create("Editing_Create", "ArticleAdmin")
.Read("Editing_Read", "ArticleAdmin")
.Update("Editing_Update", "ArticleAdmin")
.Destroy("Editing_Destroy", "ArticleAdmin")
))
</div>
in my Controller:
public ActionResult Index([DataSourceRequest] DataSourceRequest request)
{
List<ArticleViewModel> instance = new ArticleViewModel().FindByCriteria().ToList();
return View(instance); // There are some data. instance.count = 2
}
public ActionResult Editing_Read([DataSourceRequest] DataSourceRequest request)
{
List<ArticleViewModel> instance = new ArticleViewModel().FindByCriteria().ToList();
DataSourceResult dsRequest = instance.ToDataSourceResult(request); // There are some data.
return Json(dsRequest, JsonRequestBehavior.AllowGet);
}
my ViewModel:
public class ArticleViewModel : IArticle, IDateTracking
{
public ArticleViewModel()
{
}
public int? UserId { get; set; }
public string Title { get; set; }
public string Summary { get; set; }
public string Description { get; set; }
public decimal? RateCounter { get; set; }
public int? LikeCounter { get; set; }
public bool IsActive { get; set; }
public bool IsActiveNewComment { get; set; }
public IList<Comment> Comments { get; set; }
public ISet<Rating> Ratings { get; set; }
public IList<AttachmentFile> AttachmentFiles { get; set; }
public ISet<ArticleTag> ArticleTags { get; set; }
public ISet<ArticleLike> ArticleLikes { get; set; }
public int Id { get; set; }
public DateTime? CreatedDate { get; set; }
public DateTime? ModifiedDate { get; set; }
[UIHint("_TagsOfArticle")]
public virtual IList<Tag> Tags { get; set; }
public virtual int NumberOfComments { get; set; }
public virtual User User { get; set; }
private IQueryable<ArticleViewModel> QueryBuilder()
{
ArticleRepository repository = new ArticleRepository();
IQueryable<ArticleViewModel> query = repository.FindAll().Select(article => new ArticleViewModel
{
Id = article.Id,
AttachmentFiles = article.AttachmentFiles.Where(a => a.ArticleId == article.Id).Distinct().ToList(),
Comments = article.Comments.Where(c => c.ArticleId == article.Id).ToList(),
CreatedDate = article.CreatedDate,
//Description = article.Description,
IsActive = article.IsActive,
IsActiveNewComment = article.IsActiveNewComment,
LikeCounter = article.LikeCounter,
ModifiedDate = article.ModifiedDate,
NumberOfComments = article.Comments.Count(c => c.ArticleId == article.Id),
RateCounter = article.RateCounter,
//Summary = article.Summary,
Tags = article.ArticleTags.Where(c => c.ArticleId == article.Id).Select(b => b.Tag).Distinct().ToList(),
Title = article.Title,
UserId = article.UserId
});
return query;
}
public virtual IQueryable<ArticleViewModel> QueryBuilderByCriteria(Expression<Func<ArticleViewModel, bool>> predicate = null, params Expression<Func<ArticleViewModel, object>>[] includeProperties)
{
IQueryable<ArticleViewModel> items = QueryBuilder();
if (includeProperties != null)
{
foreach (Expression<Func<ArticleViewModel, object>> includeProperty in includeProperties)
{
items = items.Include(includeProperty);
}
}
if (predicate != null)
return items.Where(predicate);
return items;
}
public virtual IEnumerable<ArticleViewModel> FindByCriteria(Expression<Func<ArticleViewModel, bool>> predicate = null, params Expression<Func<ArticleViewModel, object>>[] includeProperties)
{
List<ArticleViewModel> result = QueryBuilderByCriteria(predicate, includeProperties).ToList();
return result;
}
public virtual ArticleViewModel FindByArticleId(int articleId)
{
ArticleViewModel result = QueryBuilder().FirstOrDefault(a => a.Id == articleId);
return result;
}
}
For solving the problem I performed some changes.
1) Instead of using Tag model, I've used TagViewModel.I've figured out Tag model, itself is cause of problem! I don't know why does it cause. Then I decided to create a TagViewModel that it has simplified of Tag class.
public class TagGridViewModel
{
public virtual int Id { get; set; }
public virtual string Title { get; set; }
public virtual string Description { get; set; }
public virtual bool? IsActive { get; set; }
public virtual int Size { get; set; }
public static List<TagGridViewModel> GetByArticleId(int articleId)
{
List<TagGridViewModel> tags = new List<TagGridViewModel>();
List<Tag> tagsPerArticle = ArticleRepository.Instance.GetTagsByArticleId(articleId);
foreach (var tag in tagsPerArticle)
{
tags.Add(new TagGridViewModel
{
Id = tag.Id,
IsActive = tag.IsActive,
Description = tag.Description,
Title = tag.Title,
Size = tag.Size
});
}
return tags;
}
}
And in ArticleViewModel:
public List<TagGridViewModel> Tags { get; set; }
And in FindByCriteria method:
public virtual IEnumerable<ArticleViewModel> FindByCriteria(Expression<Func<ArticleViewModel, bool>> predicate = null, params Expression<Func<ArticleViewModel, object>>[] includeProperties)
{
List<ArticleViewModel> result = new List<ArticleViewModel>();
var query = QueryBuilderByCriteria(predicate, includeProperties);
foreach (var articleViewModel in query)
{
articleViewModel.Tags = TagGridViewModel.GetByArticleId(articleViewModel.Id);
articleViewModel.Owner = AppUserStore.Instance.FindByIdAsync(int.Parse(articleViewModel.UserId.ToString())).Result.UserName;
result.Add(articleViewModel);
}
return result;
}
After these changes, Grid shows data.

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

Resources