I create kendo grid in my view but there`s no value display in my kendo grid and this is my code in chtml
<div style="width:100%;height:100%">
#(Html.Kendo().Grid<TBSWebApp.Models.DisplayRecords>()
.Name("BindGridUsingRead")
.DataSource(DataSource => DataSource.Ajax()
.Model(Model => Model.Id(m => m.InvoiceNo))
.Read(read => read.Action("BindGrid2", "Invoice")))
.Columns(columns =>
{
columns.Bound(p => p.InvoiceNo).Width(15).Title("Invoice
No.").Filterable(false);
columns.Bound(p => p.InvoiceDate).Title("Invoice
Date").Width(15).Filterable(false);
columns.Bound(p => p.FileAs).Title("Client
Name").Width(50).Filterable(false);
columns.Bound(p =>
p.Amount).Title("Amount").Width(15).Filterable(false);
})
.Pageable()
.Sortable()
)
</div>
and i have controlled which i call for my database in sql and this is the code is to bind my kendo grid to display my database and convert into json.
public ActionResult BindGrid2([DataSourceRequest]DataSourceRequest request)
{
try
{
string FileAs = "";
List<Models.DisplayRecords> lst = new List<Models.DisplayRecords>();
lst = GetGridData(FileAs).ToList();
DataSourceResult result = lst.ToDataSourceResult(request, p => new Models.DisplayRecords
{
InvoiceNo = p.InvoiceNo,
InvoiceDate = p.InvoiceDate,
FileAs = p.FileAs,
Amount = p.Amount,
});
//return Json(result, JsonRequestBehavior.AllowGet);
return Json(result);
}
catch (Exception ex)
{
var errorMsg = ex.Message.ToString();
return Json(errorMsg, JsonRequestBehavior.AllowGet);
}
}
and this one is to call sql server connection and select from the table that i want to bind it
public IEnumerable<Models.DisplayRecords> GetGridData(string ClientName)
{
List<Models.DisplayRecords> objCmp = new List<Models.DisplayRecords>();
List<Models.DisplayRecords> listCompany = new List<Models.DisplayRecords>();
string strServer = GlobalVariable.prServer;
string strDatabase = GlobalVariable.prDatabase;
string mainconn = string.Format(ConfigurationManager.ConnectionStrings["BackendEntities"].ConnectionString, strServer, strDatabase);
SqlConnection sqlconn = new SqlConnection(mainconn);
string s1 = "SELECT InvoiceNo,InvoiceDate,FileAs,LoanBalance FROM tblInvoice LEFT OUTER JOIN tblContacts ON tblInvoice.CustomerID = tblContacts.ContactID WHERE LEFT(InvoiceNo,2) ='LR'";
SqlCommand sqlcomm = new SqlCommand(s1);
sqlcomm.Connection = sqlconn;
sqlconn.Open();
SqlDataReader sdr = sqlcomm.ExecuteReader();
List<DisplayRecords> objmodel = new List<DisplayRecords>();
if (sdr.HasRows)
{
while (sdr.Read())
{
objCmp.Add(new Models.DisplayRecords() { InvoiceNo = sdr["InvoiceNo"].ToString(), InvoiceDate = sdr["InvoiceDate"].ToString(), FileAs = sdr["FileAs"].ToString(), Amount = sdr["LoanBalance"].ToString() });
}
sqlconn.Close();
}
if (ClientName != "")
{
listCompany = objCmp.ToList().Where(a => a.FileAs == ClientName).ToList();
return listCompany.AsEnumerable();
}
return objCmp.ToList().AsEnumerable();
}
but the result is still no data display in my kendo grid. I dont know why but when i try to break point on my controller action the "public ActionResult BindGrid2" is not passing by and this is the result of running web view:
Click to view Image
Related
i using ajax for reading data from my controller(ShiftReports).and i also using view model for combine two tables.
i don't now how to binding or iterate json array to kendo column.
this is my kendo mvc grid
#(Html.Kendo().Grid<PLIMO.ViewModel.MainEqpViewModel>()
.Name("MainEQP")
.DataSource(ds => ds
.Ajax()
.Read(read => read.Action("Eqp_Read", "ShiftReports"))
)
.Pageable()
.Sortable()
)
this is my controller
public ActionResult Eqp_Read([DataSourceRequest]DataSourceRequest request)
{
try {
using (var db = new DBContext())
{
db.Configuration.ProxyCreationEnabled = false;
var eqp = new MainEqpViewModel()
{
Tags = db.Tags.ToList(),
};
DataSourceResult result = new List<MainEqpViewModel>() { eqp }.ToDataSourceResult(request);
return Json(result);
}
}
catch(Exception ex)
{
return Json(ex.Message);
}
}
}
You need a dynamic column. please refer the sample code https://dotnetlearningarray.blogspot.com/2015/06/telerik-mvc-grid-with-dynamic-columns.html
I'm trying to add to the JsonResult object a parsed Json string, but I couldn't do it, the parser object in the browser is shown as:
"filter":[[[]],[[[],[]]]]
This is the full code
public JsonResult AjaxStandardGet(int id)
{
Standard ec = db.Standard.FirstOrDefault(s => s.IdStandard == id);
// inside filter: { "KeyDynamic1": "Value1", "KeyDynamic2": [ "AAA", "DDD"] }
var filter = JsonConvert.DeserializeObject(ec.Filter);
return Json(new
{
ec.IdStandard,
ec.Description,
filter,
ec.Observations,
Services = ec.StandardServices.Select(s => new {
s.IdStandardServices,
Tecnology = s.Tecnology?.Nombre,
ServiceType = s.ServiceType?.Description,
s.Quantity,
s.Cost,
Options = (!string.IsNullOrEmpty(s.Options) ? s.Options.Split(',') : null),
Total = s.Quantity * s.Cost
}),
Success = true
});
}
I can't create the model object because the filters are not allways the same.
I tried this:
Dictionary<string, object> filter = JsonConvert.DeserializeObject<Dictionary<string, object>>(ec.Filter);
And I get
"filter":{"KeyDynamic1":"Value1","KeyDynamic2":[[],[]]}
I suggest you to JToken or dynamic:
JToken filter = JToken.Parse(ec.Filter);
dynamic filter = JsonConvert.DeserializeObject<dynamic>(ec.Filter);
Here is working fiddle.
Update
It seems that JavaScriptSerializer is not able to do it. So you can serialize your result using Newtonsoft.Json and return it as a string:
var result = new
{
ec.IdStandard,
ec.Description,
filter,
ec.Observations,
Services = ec.StandardServices.Select(s => new {
s.IdStandardServices,
Tecnology = s.Tecnology?.Nombre,
ServiceType = s.ServiceType?.Description,
s.Quantity,
s.Cost,
Options = (!string.IsNullOrEmpty(s.Options) ? s.Options.Split(',') : null),
Total = s.Quantity * s.Cost
}),
Success = true
};
var json = JsonConvert.SerializeObject(result);
return Content(json, "application/json");
I want to validate #Html.EditorFor that it is required to input, but not working in asp.net mvc
<div class="form-group"> <label>First Name editor*</label>
#Html.EditorFor(x => x.Requester.FirstName, new { #class = "form-control", required = "required" })
#Html.ValidationMessageFor(m => m.Requester.FirstName)
</div>
sorry for my simple question because it is really frustating try to fix this issue
my controller code
[HttpPost]
public ActionResult Index(ViewModel.Ticket m)
{
try
{
using (DatabaseManager ctx = new DatabaseManager(true))
{
if (string.IsNullOrEmpty(m.TicketNo))
{
m.TicketNo = TicketNo.Create(User.Identity.Name, "TICKET");
}
Ticket obj = ViewModel.Ticket.ConvertToTicketBusiness(m);
obj.Requester = m.Requester.Email;
obj.TicketStatus = TicketStatus.Open.ToString();
obj.Escalation = User.Identity.Name;
obj.CreatedBy = User.Identity.Name;
obj.CreatedDate = DateTime.Now;
obj.UpdatedBy = obj.CreatedBy;
obj.UpdatedDate = obj.CreatedDate;
if (obj.IsValid)
{
obj = obj.Save();
}
Customer cust = ViewModel.Ticket.ConvertToCustomerBusiness(m.Requester);
if (string.IsNullOrEmpty(cust.CreatedBy))
{
cust.CreatedBy = User.Identity.Name;
cust.CreatedDate = DateTime.Now;
}
cust.UpdatedBy = User.Identity.Name;
cust.UpdatedDate = DateTime.Now;
if (cust.IsValid)
{
cust = cust.Save();
}
ctx.SaveChanges();
}
ViewBag.SuccessMsg = "Success";
}
catch (Exception ex)
{
ViewBag.ErrorMsg = ex.Message;
return View(m);
}
return RedirectToAction("Inbox");
}
thank you
Insert # Like: #required="required"
This is how it worked for me (ASP.NET MVC 5). Add
#data_val="true"
with
#required="required"
Final code:
#Html.EditorFor(model => model.FullName, new { htmlAttributes = new { #class = "form-control", #data_val="true", #required="required" } })
by adding , the form started to use jquery validator.
When you want to validate mandatory form input do not use EditorFor() if your MVC bellow 5.1, just using TextBoxFor() thank you
I need to insert a default value at the top of the result I have as below....
Can someone give me a clue how to do it with an anonymous type?
public JsonResult GetThingsForStuff(string stuff)
{
var things= from c in db.MYTABLE
where c.idofstuff == stuff
select new { id = c.realid, name = c.realname};
return Json(things, JsonRequestBehavior.AllowGet);
}
In my controller I do this initially by
List<SelectListItem> items3 = new SelectList(db.MYTABLE.ToList().Distinct(), "realid", "realname").ToList();
items3.Insert(0, (new SelectListItem { Text = "Select Me", Value = "0" }));
ViewBag.Things = items3;
by I have a javascript function reloading this dropdownlist based on the selected "stuff" and I need this default back at the top.
Any help would be greatly appreciated.
Thanks,
David
You could concatenate them:
public JsonResult GetThingsForStuff(string stuff)
{
var things = db
.MYTABLE
.Where(x => x.idofstuff == stuff)
.ToList()
.Select(x => new SelectListItem
{
Value = x.realid.ToString(),
Text = x.realname
});
var items = new[] { new SelectListItem { Text = "Select Me", Value = "0" } }
.Concat(things);
return Json(items, JsonRequestBehavior.AllowGet);
}
Im having problem with rebinding grid with Json object….
Im trying to create custom delete button…
So far I have Jquery function: Gets an ID of selected column (username) and call controller action “UserDetails”
Delete button:
$("#DeleteUser").click(function () {
if (id != "") {
var answer = confirm("Delete user " + id)
if (answer) {
$.ajax({
type: "POST",
url: "/Admin/UserDetails",
data: "deleteName=" + id,
success: function (data) {
}
});
}
} else {
$("#erorMessage").html("First you must select user you whant to delete!");
}
});
This is action controller UserDetails(string startsWith, string deleteName)
[GridAction]
public ActionResult UserDetails(string startsWith, string deleteName)
{ // Custom search...
if (!string.IsNullOrEmpty(startsWith))
{
return GetSearchUserResult(startsWith);
}
if (!string.IsNullOrEmpty(deleteName))
{
TblUserDetails user = db.TblUserDetails.Single(a => a.TblUser.userName == deleteName);
try
{
TblUser userToDelete = db.TblUser.Single(a => a.userId == user.TblUser.userId);
db.DeleteObject(user);
db.DeleteObject(userToDelete);
db.SaveChanges();
Membership.DeleteUser(deleteName);
List<UserDto> retModelData = new List<UserDto>();
//GetAllUsers() returns a List<UserDto> of users.
retModelData = GetAllUsers();
var model = new GridModel
{
Data = retModelData,
Total = GetAllUsers().Count()
};
return View(model);
}
catch
{
return View(new GridModel());
}
}
else
{
var user = GetAllUsers();
return View(new GridModel(user));
}
}
So far everything is working OK. But can I bind my grid with these Json data and how???
This is my Json result that I want to bind with grid...
And here is my grid:
#(Html.Telerik().Grid<App.Web.Models.UserDto>()
.Name("Grid")
.DataKeys(key =>
{
key.Add(a => a.Id);
})
.Columns(column =>
{
column.Bound(a => a.Username).Filterable(false);
column.Bound(a => a.FirstName).Filterable(false);
column.Bound(a => a.LastName).Filterable(false);
column.Bound(a => a.Email).Filterable(false);
})
.DetailView(detailView => detailView.ClientTemplate(
"<table id='DetailTable'><tbody><tr class='UserRow'><td class='Tbllable'><b>First name</b></td><td><#= FirstName #></td>"
+ "<td></td><td></td>"
+ "</tr><tr><td class='Tbllable'><b>Last name</b></td>"
+ "<td><#= LastName #></td>"
+ "<td id='Roles'></td><td id='Operations'></td>"
+ "</tr><tr><td class='Tbllable'><b>Username</b></td><td><#= Username #></td></tr><tr><td class='Tbllable'><b>Address</b></td>"
+ "<td><#= Address #></td></tr><tr><td class='Tbllable'><b>Email</b></td><td><#= Email #></td></tr><tr><td class='Tbllable'><b>Birth date</b></td>"
+ "<td></td></tr><tr><td class='Tbllable'><b>Registration date</b></td><td></td></tr><tr><td class='Tbllable'><b>Phone number</b></td>"
+ "<td><#= PhoneNumberHome #></td></tr><tr><td class='Tbllable'><b>Mobile number</b></td><td><#= PhoneNumberMobile #></td></tr></tbody></table>"
))
//.EnableCustomBinding(true)
.DataBinding(bind => bind.Ajax().Select("UserDetails", "Admin", new { startsWith = ViewBag.startsWith }))
.Pageable(paging =>
paging.PageSize(12)
.Style(GridPagerStyles.NextPreviousAndInput)
.Position(GridPagerPosition.Bottom)
)
.ClientEvents(e => e
.OnRowDataBound("Expand")
.OnRowSelect("select")
.OnLoad("replaceConfirmation")
)
.RowAction(row =>
{
if (row.Index == 0)
{
row.DetailRow.Expanded = true;
}
})
.Editable(editing => editing.Mode(GridEditMode.PopUp))
.Selectable()
.Sortable()
)