mvc - jQuery ajax datatable actionlink - asp.net-mvc

I have a datatable in which the data (from the database) is being filled with ajax, I also want a new tablerow with "Details" to show more details of the selected item, but the table only allows data from the database. Here is the view
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$('#myDataTable').dataTable({
"bProcessing": false,
"bServerSide": true,
"sAjaxSource": 'AjaxDataProvider',
"aoColumns": [
{
"sName": "ID",
},
{ "sName": "Student_naam" },
{ "sName": "klas" },
{ "sName": "adres" },
{ "sName": "woonplaats" },
{ "sName": "details" }
]
})
});
</script>
and I have a table beneath with some code including this:
<td>
#Html.ActionLink("Details", "Index", "StudentGegevens", new {id = item.studentnr})
</td>
Here is my controller
public ActionResult AjaxDataProvider(JQueryDataTableParamModel param)
{
var allStudents = hoi.STUDENT.ToList();
IEnumerable<STUDENT> filteredStudents;
if (!string.IsNullOrEmpty(param.sSearch))
{
//Used if particulare columns are filtered
var roepnaamFilter = Convert.ToString(Request["sSearch_1"]);
var adresFilter = Convert.ToString(Request["sSearch_2"]);
var woonplaatsFilter = Convert.ToString(Request["sSearch_3"]);
var klasFilter = Convert.ToString(Request["sSearch_4"]);
//Optionally check whether the columns are searchable at all
var isNameSearchable = Convert.ToBoolean(Request["bSearchable_1"]);
var isAddressSearchable = Convert.ToBoolean(Request["bSearchable_2"]);
var isTownSearchable = Convert.ToBoolean(Request["bSearchable_3"]);
var isClassSearchable = Convert.ToBoolean(Request["bSearchable_4"]);
filteredStudents = hoi.STUDENT.ToList()
.Where(c => isNameSearchable && c.roepnaam.ToLower().Contains(param.sSearch.ToLower())
||
isAddressSearchable && c.adres.ToLower().Contains(param.sSearch.ToLower())
||
isTownSearchable && c.woonplaats.ToLower().Contains(param.sSearch.ToLower())
||
isClassSearchable && c.klas.ToLower().Contains(param.sSearch.ToLower()));
}
else
{
filteredStudents = allStudents;
}
var isNameSortable = Convert.ToBoolean(Request["bSortable_1"]);
var isAddressSortable = Convert.ToBoolean(Request["bSortable_2"]);
var isTownSortable = Convert.ToBoolean(Request["bSortable_3"]);
var isClassSortable = Convert.ToBoolean(Request["bSortable_4"]);
var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
Func<STUDENT, string> orderingFunction = (c => sortColumnIndex == 1 && isNameSortable ? c.roepnaam :
sortColumnIndex == 2 && isClassSortable ? c.klas :
sortColumnIndex == 3 && isAddressSortable ? c.adres :
sortColumnIndex == 4 && isTownSortable ? c.woonplaats :
"");
var sortDirection = Request["sSortDir_0"]; // asc or desc
if (sortDirection == "asc")
{
filteredStudents = filteredStudents.OrderBy(orderingFunction);
}
else
{
filteredStudents = filteredStudents.OrderByDescending(orderingFunction);
}
var displayedStudents = filteredStudents.Skip(param.iDisplayStart).Take(param.iDisplayLength);
var result = from c in displayedStudents select new[] { Convert.ToString(c.studentnr), c.roepnaam, c.klas, c.adres, c.woonplaats, "Here is the thing I dont know what to fill in" };
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = allStudents.Count(),
iTotalDisplayRecords = filteredStudents.Count(),
aaData = result
},
JsonRequestBehavior.AllowGet);
}
And some public ints
public class JQueryDataTableParamModel
{
public string sEcho { get; set; }
public string sSearch { get; set; }
public int iDisplayLength { get; set; }
public int iDisplayStart { get; set; }
public int iColumns { get; set; }
public int iSortingCols { get; set; }
public string sColumns { get; set; }
}
I would like to know what I should put at the var Result.
everything is displayed correctly except the link, I tried something like Url.Action but without luck, it doesn't give a link back.

Not very sure what kind of detail data that you want to show, but you can check the method: fnrender or mRender, below is a sample.
"aoColumns": [
{
"sName": "ID",
},
{ "sName": "Student_naam" },
{ "sName": "klas" },
{ "sName": "adres" },
{ "sName": "woonplaats" },
{ "sName": "details",
"mRender": function ( data, type, full ) {
return 'Download';
} }
]

Sorry, I'm a dumbass, I remembered I could put string in the controller with HTML and it would convert it to HTML ->.
var result = from c in displayedStudents select new[] { Convert.ToString(c.studentnr), c.roepnaam, c.klas, c.adres, c.woonplaats, "<a style='font-family:arial' href='" + "../StudentGegevens/index/" + c.studentnr + "' />Details</a>"};
lol, not the brightest person I am, I'm sorry for asking this question.

Related

how to return back list of data from controller to knockout function to view page

This is my controller where i am returning back list of tags with the post:
public JsonResult GetPosts(int? id)
{
var varid = id;
var ret = (from post in db.Posts.ToList()
orderby post.PostedDate descending
select new
{
CityName = post.City.CityName,
TagName = post.Tags.ToList()
// TagName = post.Tags
}
}
I dont know, here, is this the way to return back all the tags selected.
Posts and Tags table are interconnected by many to many relation with a join table TagPost in database which contains TagId and PostId.
this is the knockout code:
function Post(data) {
var self = this;
data = data || {};
self.CityName = data.CityName || "";
self.TagName = data.TagName || "";
}
function viewModel() {
var self = this;
self.posts = ko.observableArray();
self.newMessage = ko.observable();
self.error = ko.observable();
self.loadPosts = function () {
// to load existing posts
$.ajax({
url: postApiUrl1,
data: { id: $("#Locations").val() },
datatype: "json",
contentType: "application/json",
cache: false,
type: 'Get'
})
.done(function (data) {
var mappedPosts = $.map(data, function (item)
{ return new Post(item); });
self.posts(mappedPosts);
})
.fail(function () {
error('unable to load posts');
});
}
This is the view page where i want to data-bind the cityName along with the tags:
<div>
<img src="~/assests/images/icon.png" alt=""><span><a data-bind="text: CityName"></a></span>
</div>
<div>
<img src="~/assests/images/tag.png" alt=""><span><a data-bind="text: TagName"></a></span>
</div>
Here, i want to return back all the tag name with comma seperated.Please someone suggest me what to do from here.
This is my Post class:
public class Post
{
[Key]
public int PostId { get; set; }
public string Message { get; set; }
public int? cityId { get; set; }
public IList<Tag> Tags { get; set; }
}
and this is my tag class:
public class Tag
{
public int TagId { get; set; }
public string TagName { get; set; }
public IList<Post> Posts { get; set; }
}
There is a many to many relationship between tag and post class so its creating a new join Table TagPost with column(TagId, PostId).
This is how i am inserting data to this table with on model creating:
modelBuilder.Entity<Tag>()
.HasMany(p => p.Posts)
.WithMany(t => t.Tags)
.Map(m =>
{
m.ToTable("TagPost");
m.MapLeftKey("TagId");
m.MapRightKey("PostId");
});
This should bring the data in the format you want:
var data = db.Posts.Include(x => x.Tags)
.Include(x => x.City)
.Where(x => x.PostId == id)
.SingleOrDefault();
var json = new {
PostId = data.PostId,
PostMessage = data.Message,
CityName = data.City.CityName,
Tags = string.Join(",", data.Tags.Select(t => t.TagName))
};
return Json(json, JsonRequestBehavior.AllowGet);
This will return the following Json:
{
"PostId": 1,
"PostMessage": "ABC",
"CityName": "Chicago",
"Tags": "C#,.NET,StackOverflow"
}
Just note that I've included the City using Include in the Post but in the model you posted, there's only the cityId. Perhaps you'll need to change that too.
EDIT
As per request, to return all posts and related tags change the code to this:
var data = db.Posts.Include(x => x.Tags)
.Include(x => x.City)
.ToList();
if (data.Count == 0)
return null; //Just return something if no post is found
var json = data.Select(x => new
{
PostId = x.PostId,
PostMessage = x.Message,
CityName = x.City.CityName,
Tags = string.Join(",", x.Tags.Select(t => t.TagName))
}).ToList();

How to send message/notification to browser/client in Kendo Mvc Ajax Bound Grid (confirm update or create) ( by cookies)

how to send notification to client in kendo mvc ajax bound ,
i do not know if this is good way ..
of course you can add ModelState.AddModelError("notification","….msg.")
and …. But it tell to datasource ajax action failed.. So..
Addclass:
public class AjaxErrorMsg
{
public AjaxErrorMsg()
{
CssClass = "gray";
AutoHide = false;
AutoHideDelay = 200;
Kind = "error";
Title = "error";
}
public string Msg { get; set; }
public string Kind { get; set; }
public Boolean AutoHide { get; set; }
public Int32 AutoHideDelay { get; set; }
public string CssClass { get; set; }
public string Title { get; set; }
}
In controller
public void StoreMessageInCookie(string msg, Boolean isError = false, string msgDivClass = "", string preMessage = "", string msgTitle = "")
{
StoreMessageInCookie(new Exception(msg), isError, msgDivClass, preMessage, msgTitle);
}
public void StoreMessageInCookie(Exception ee, Boolean isError = false, string msgDivClass = "", string preMessage = "", string msgTitle = "")
{
List<AjaxErrorMsg> rs;
var js = new JavaScriptSerializer();
if (this.Response.Cookies[Common1.MsgCookie].HasKeys )
{
try
{
rs = js.Deserialize<List<AjaxErrorMsg>>(this.Response.Cookies[Common1.MsgCookie].Value);
}
catch
{
rs = new List<AjaxErrorMsg>();
}
}
else
{
rs = new List<AjaxErrorMsg>();
}
var msg0 = new AjaxErrorMsg();
if (isError)
{
msgDivClass = msgDivClass == "" ? "DivAlarmStyle6 fontMitra" : msgDivClass;
msg0.Kind = "error";
msg0.AutoHide = false;
msg0.Title = "Error";
}
else
{
msg0.Kind = "alert";
msg0.AutoHide = true;
msg0.Title = "Warning";
}
msg0.Title = msgTitle == "" ? msg0.Title : msgTitle;
msg0.Msg = preMessage + cm2.FilterMessageText(ee, IsAdminUser);
if (msgDivClass.Trim() != "")
msg0.Msg = Common1.WrapTextInDivWithClass(msg0.Msg, msgDivClass);
rs.Add(msg0);
this.Response.Cookies.Add(new HttpCookie(Common1.MsgCookie, js.Serialize(rs)));
}
cm2.FilterMessageText is function to remove database object name from error message string ..also include any inner exception message
Then when you what to send message use command
StoreMessageInCookie("Message 1 2 ! ");
And in your MainProject.js
Add all of code below
function createCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ')
c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length, c.length);
}
return null;
}
function ReadAnShowCookieForDeliverMessages() {
try {
var listMsg = readCookie("CookieForDeliverMessages")
if (!!listMsg) {
eraseCookie("CookieForDeliverMessages");
ShowAndLogMessageListOfAjaxError($.parseJSON(listMsg));
}
} catch (ee) {
alert(" error in ReadAnShowCookieForDeliverMessages")
}
}
function ShowAndLogMessageListOfAjaxError(ListOfAjaxError) {
if (ListOfAjaxError == undefined)
return;
ListOfAjaxError.forEach(function (AjaxError) {
ShowAndLogMessageByAjaxErrorClass(AjaxError)
})
}
function ShowAndLogMessageByAjaxErrorClass(AjaxError) {
if ((AjaxError != undefined) && (AjaxError.Msg != "")) {
// I used freeow => https://github.com/pjdietz/Freeow
$("#freeow").freeow(AjaxError.Title, AjaxError.Msg, { classes: [AjaxError.CssClass, AjaxError.Kind], autoHide: AjaxError.AutoHide, autoHideDelay: AjaxError.AutoHideDelay });
// LogMsg(AjaxError.Msg, AjaxError.Title); function to log message on client
}
}
$(function () {
MyAjaxSetting();
ReadAnShowCookieForDeliverMessages();
}
function MyAjaxSetting() {
$(document).ajaxComplete(function (o) {
ReadAnShowCookieForDeliverMessages()
});
}

Not Get data in jstree

I am create menu of Category and SubCategory in my project using jstree.
but i do not get or not show my data in jstree format.
so, what is problem.?
Plz Help me.
thnks....
My Controller Code
[HttpGet]
public JsonResult GetCatList()
{
IEnumerable<Category> cats = _CategoryBusiness.Select();
return new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = cats
};
}
My Model Class
[Serializable]
public class Category
{
[Key]
[DisplayName("Id")]
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public int? SubCategoryID { get; set; }
[ForeignKey("SubCategoryID")]
public virtual Category SubCategory { get; set; }
}
And _CategoryBusiness.Select() is
public List<Category> Select(int id = 0)
{
var selectFrom = _Ctx.Categories.Select(a => a);
var query = selectFrom.Select(a => a);
if(id > 0)
query = query.Where(a => a.CategoryID == id);
return query.ToList();
}
And My View Page code is
<script type="text/javascript">
$(function () {
FillJSTree();
});
function FillJSTree() {
$("#onflycheckboxes").jstree({
json_data: {
"ajax": {
"url": "/Categories/GetCatList/",
"type": "GET",
"dataType": "json",
"contentType": "application/json charset=utf-8",
}
},
//checkbox: {
// real_checkboxes: true,
// checked_parent_open: true
//},
plugins: ["themes", "json_data", "ui"]
});
}
</script>
.
.
.
.
..
<div id="onflycheckboxes">
</div>
Try this: Before sending data to view, serialize that. This works for me. P.s. Your category data must be tree node.
[HttpGet]
public string GetCatList()
{
IEnumerable<Category> cats = _CategoryBusiness.Select();
string myjsonmodel = new JavaScriptSerializer().Serialize(cats);
return myjsonmodel;
}

Why Breeze jquery Where/Take/Order dont work in BreezeJs without nodb,

Here is my code:
Server-Web API
=======================================
public class OwnerDto {
public int OwnerId { set; get; }
public string OwnerName { set; get; }
}
[HttpGet]
public IEnumerable GetOwner()
{
IEnumerable result = new[] {
new OwnerDto { OwnerId = 1, OwnerName = "Test1" },
new OwnerDto { OwnerId = 2, OwnerName = "Test2" },
new OwnerDto { OwnerId = 3, OwnerName = "Test3" },
new OwnerDto { OwnerId = 4, OwnerName = "Test4" }
};
return result;
}
js code
var dataService = new breeze.DataService({
serviceName: "/api/owner/",
hasServerMetadata: false,
});
var manager = new breeze.EntityManager({ dataService: dataService });
var store = manager.metadataStore;
//metadataStore.namingConvention = namingConv;
store.addEntityType({
shortName: "Owner",
namespace: "Test.Owner",
dataProperties: {
OwnerId: { dataType: breeze.DataType.Int32, isPartOfKey: true },
OwnerName: { dataType: breeze.DataType.String}
}
});
var op = breeze.FilterQueryOp;
var query = new breeze.EntityQuery()
.from("GetOwner")
.where("ownerId",op.Equals,2);
manager.executeQuery(query).then(function (data) {
ko.applyBindings(data, $("#SearchResult")[0]);
}).fail(function (e) {
alert(e);
});
Html Code
p- data-bind="visible: !results" Fetching data ..
ul- data-bind="foreach: results, visible: results" style="display:none"
span- data-bind="text: OwnerName"
span- data-bind="text: OwnerId"
==========================================
The problem is all the data can display but the filter(where/take/order...) does not work.
Any ideas, Thanks very much!
I believe the reason is that the method on your query returns IEnumerable. Those verbs (where/take/order) only apply to service endpoints that return IQueryable<T>. Try this:
[HttpGet]
public IQueryable GetOwner()
{
IEnumerable result = new[] {
new OwnerDto { OwnerId = 1, OwnerName = "Test1" },
new OwnerDto { OwnerId = 2, OwnerName = "Test2" },
new OwnerDto { OwnerId = 3, OwnerName = "Test3" },
new OwnerDto { OwnerId = 4, OwnerName = "Test4" }
};
return result.AsQueryable();
}

MVC populate drop down list no postback

Is their a way to populate a drop down list by pressing a button without post back.
Ex: dropdownlist1 -> a
press button
and populates dropdownlist2 with different data regarding dropdownlist1 value.
Thanks
Most common scenario is generating the second dropdownlist values depending on the first DropDownList selected item changed. I assume that you are looking for the same scenario and below code is for achieve that. Let me know if you really need the button click to generate the second dropdown.
Model:
namespace MvcApplicationrazor.Models
{
public class CountryModel
{
public List<State> StateModel { get; set; }
public SelectList FilteredCity { get; set; }
}
public class State
{
public int Id { get; set; }
public string StateName { get; set; }
}
public class City
{
public int Id { get; set; }
public int StateId { get; set; }
public string CityName { get; set; }
}
}
Controller:
public ActionResult Index()
{
CountryModel objcountrymodel = new CountryModel();
objcountrymodel.StateModel = new List<State>();
objcountrymodel.StateModel = GetAllState();
return View(objcountrymodel);
}
//Action result for ajax call
[HttpPost]
public ActionResult GetCityByStaeId(int stateid)
{
List<City> objcity = new List<City>();
objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
return Json(obgcity);
}
// Collection for state
public List<State> GetAllState()
{
List<State> objstate = new List<State>();
objstate.Add(new State { Id = 0, StateName = "Select State" });
objstate.Add(new State { Id = 1, StateName = "State 1" });
objstate.Add(new State { Id = 2, StateName = "State 2" });
objstate.Add(new State { Id = 3, StateName = "State 3" });
objstate.Add(new State { Id = 4, StateName = "State 4" });
return objstate;
}
//collection for city
public List<City> GetAllCity()
{
List<City> objcity = new List<City>();
objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
return objcity;
}
View:
#model MvcApplicationrazor.Models.CountryModel
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
function GetCity(_stateId) {
var procemessage = "<option value='0'> Please wait...</option>";
$("#ddlcity").html(procemessage).show();
var url = "/Test/GetCityByStaeId/";
$.ajax({
url: url,
data: { stateid: _stateId },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#ddlcity").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
</script>
<h4>
MVC Cascading Dropdown List Using Jquery</h4>
#using (Html.BeginForm())
{
#Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { #id = "ddlstate", #style = "width:200px;", #onchange = "javascript:GetCity(this.value);" })
<br />
<br />
<select id="ddlcity" name="ddlcity" style="width: 200px">
</select>
<br /><br />
}

Resources