I'm using MVC 5 C# and I'm trying to update my search filter on key strokes through AJAX. By code it works but the results aren't showing up on testing. I've done some debugging and in my view the results are being thrown in the view as shown:
It's supposed to be displayed right underneath the search box but shows nothing.
Not quite sure what the issue is. So I'll list my code. Here is my Ajax.
<p>
Search Employee: <input type="text" name="userName" onkeyup="filterTerm(this.value);" />
</p>
<script>
function filterTerm(value) {
$.ajax({
type: "POST",
url: '#Url.Action("Index", "Directory")',
data: {
userName: value
},
cache: false,
success: function (result) {
}
});
}
</script>
Ajax has been tested and is working, now in my controller it also is returning results (obviously is being pulled back to the View but just showing results).
But here is my controller anyways:
[HttpPost]
public ActionResult Index(string userName)
{
/**********Establish Connection********/
DirectoryEntry dir = createDirectoryEntry();
DirectorySearcher search = new DirectorySearcher(dir);
/****Refer to class constructor****/
/********Create the List to store results in***************/
List<ADUser> Users = new List<ADUser>();
string DisplayName = "", SAMAccountName = "", Mail = "", Description = "", Department = "", TelephoneNumber = "", Fax = "";
/*******Filter parameters************/
search.Filter = "(&((&(objectCategory=Person)(objectClass=User)))(anr=" + userName + "* ))";
SearchResultCollection searchresult = search.FindAll();
search.PropertiesToLoad.Add("Displayname");
search.PropertiesToLoad.Add("SAMAccountName");
search.PropertiesToLoad.Add("Mail");
search.PropertiesToLoad.Add("Description");
search.PropertiesToLoad.Add("TelephoneNumber");
search.PropertiesToLoad.Add("Fax");
search.PropertiesToLoad.Add("Department");
/*****************Filtering and populating the List****************/
if (searchresult != null)
{
foreach (SearchResult iResult in searchresult)
{
ADUser userAttributes = new ADUser("", "", "", "", "", "", "");
foreach (string PropertyName in iResult.Properties.PropertyNames)
{
foreach (Object key in iResult.GetDirectoryEntry().Properties[PropertyName])
{
try
{
switch (PropertyName.ToUpper())
{
.....
}
}
catch { }
}
}
Users.Add(userAttributes);
}
return View(Users);
}
return View();
}
It seems like it might just be something I'm missing that I don't know about.
Any help would be greatly appreciated.
Cheers
serialize your user list to json before return it to view as follow.
using System.Web.Script.Serialization;
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(User);
return View(json)
and make your ajax's datatype json as follow :
$.ajax({
type: "POST",
url: '#Url.Action("Index", "Directory")',
data: {
userName: value
},
dataType:"json",
cache: false,
success: function (result) {
}
});
Related
I have select2s, I fill these select2 with procedure. I fill select2 by saying return json on the controller side. But repetitive recordings are coming, where can I use DISTINCT for this?
JavaScript
$('#markaSelect').select2({
ajax: {
url: '/Home/MarkaGetir',
data: function (params) {
var query = {
q: params.term,
ModelAd: $('#modelselect').val(),
UreticiAd: $('#ureticiselect').val()
}
return query;
},
dataType: 'json',
type: "POST",
},
placeholder: 'Marka Seçiniz',
allowClear: true
});
Controller
public JsonResult MarkaGetir(string q = "", string MarkaAd = "", string ModelAd = "", string UreticiAd = "")
{
var lst = Vtİslemleri.Mmu(MarkaAd, ModelAd, UreticiAd);
lst.Select(x => x.Marka).Distinct();
return Json(new
{
results = lst.Select(x =>
new
{
id = x.Marka,
text = x.Marka
})
});
}
A short example: There are 4 of the Seat brand models, I want 1 to come when I shoot this.
I want to be able to display the ViewBag on view on button click event, this is my code:
[HttpPost]
public ActionResult SpecificWorkflowReport(Report2ListViewModel wf)
{
var getSpRecord = db.Mworkflow().ToList();
var getRecord = (from u in getSpRecord
select new Report2ListViewModel
{
WorkFlowType = u.WorkFlowType,
WorkflowInstanceId = u.WorkflowInst,
WorkFlowDescription = u.WorkFlowDesc,
}).ToList();
ViewBag.WorkflowType = wf.WorkFlowType;
ViewBag.WorkflowInstanceId = wf.WorkflowInst;
ViewBag.WorkFlowDescription = wf.WorkFlowDesc
var data = Newtonsoft.Json.JsonConvert.SerializeObject(getRecord);
return Json(data);
}
i have tried this:
Worflow Type: #ViewBag.WorkflowType
Workflow Instance Id: #ViewBag.WorkflowInstanceId
Workflow Description: #ViewBag.WorkFlowDescription
My Javascript and json Call:
<script type="text/javascript">
$(function () {
var table = $("#reportTable").DataTable();
var url = $("#frmSpecificWorkflowReport").attr('action');
var str = $("#frmSpecificWorkflowReport").serialize();
$.ajax({
url: url,
type: "POST",
data: str,
cache: false,
dataType: "json",
success: function (_data) {
if (_data.f !== undefined) {
swal({
title: "Empty Result Set",
text: "No record found",
type: "info"
});
table.clear();
return false;
}
var arr = $.map(JSON.parse(_data), function (el) { return el
});
if (arr.length === 0) {
swal({
title: "Empty Result Set",
text: "No record found",
type: "info"
});
}
table.clear();
table.destroy();
$('#reportTable').dataTable({
data: arr,
columns: [
{ "data": "WorkFlowType" },
{ "data": "WorkflowInstanceId" },
{ "data": "WorkFlowDescription" },
],
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel',
{
extend: 'pdfHtml5',
orientation: 'landscape',
pageSize: 'LEGAL'
}
]
});
table = $("#reportTable").DataTable();
but the ViewBag values are always null on the view, any assistance will be appreciated. I just added Javascript and json call to the post, i want to be able to retrieve my stored data and display it anywhere on the view
#UwakPeter your code snippets is ok, but you are returning Json, may be you are calling this method via javascript, so the view is not updating, you need to reload the view, by the submit button.
If you are using javascript, you can pass your data list and model data as anonymous object, so that you don't need to use ViewBag. in client side by ajax success function you can grab them (WorkflowType, WorkflowInstanceId, WorkFlowDescription, Result)
[HttpPost]
public ActionResult SpecificWorkflowReport(Report2ListViewModel wf)
{
var getSpRecord = db.Mworkflow().ToList();
var getRecord = (from u in getSpRecord
select new Report2ListViewModel
{
WorkFlowType = u.WorkFlowType,
WorkflowInstanceId = u.WorkflowInst,
WorkFlowDescription = u.WorkFlowDesc,
}).ToList();
var data = Newtonsoft.Json.JsonConvert.SerializeObject(getRecord);
return Json(new{
WorkflowType = wf.WorkFlowType,
WorkflowInstanceId = wf.WorkflowInst,
WorkFlowDescription = wf.WorkFlowDesc,
Result= data
}, JsonRequestBehaviour.AllowGet);
}
JS
$.ajax({
url: url,
type: "POST",
data: str,
cache: false,
dataType: "json",
success: function (_data) {
var workflowType=_data.WorkflowType; //set it to HTML control
var workflowInstanceId =_data.WorkflowInstanceId;
var workFlowDescription = _data.WorkFlowDescription;
$('#reportTable').dataTable({
data: _data.Result
});
}
)};
Try this,
#{
Layout = null;
ProjectMVC.Models.Record record= (ProjectMVC.Models.Record)ViewBag.Recorddetails;
}
...
Worflow Type: #record.WorkflowType
I am relatively new in MVC and C#, and i am having a lot of problems to learn some little things. I am having some errors and would like any help to solve my problem.
I have these 2 models:
UsuarioDal:
public Usuario LoginById(int Id)
{
var login = (from u in db.Usuario
where u.IdUsuario == Id && u.Ativo == true
select u).FirstOrDefault();
return login;
}
UsuarioDeviceDal:
public UsuarioDevice getByUUID(string uuid)
{
var usuariodevice = (from c in db.UsuarioDevice
where c.UuId == uuid
select c).FirstOrDefault();
return usuariodevice;
}
Controller:
public HttpResponseMessage GetConsultaLogUsu(string uuid){
UsuarioDeviceDAL dev = new UsuarioDeviceDAL();
UsuarioDAL obj = new UsuarioDAL();
var device = dev.getByUUID(uuid);
var usu obj.LoginById(device.IdUsuario); // this is the line that i would like to work.
if (device != null){
return new HttpResponseMessage(){
Content = new StringContent("L")
};
}else{
return new HttpResponseMessage(){
Content = new StringContent("D")
};
}
}
Ajax:
function fn_verificalog() {
var uuid = $("#uuid").val();
$.ajax({
type: "GET",
url: linkServidor + "api/GuardaUsuario/GetConsultaLogUsu?uuid="+uuid,
contentType: "application/json",
success: function (data) {
navigator.notification.alert(data, fn_ErroApp(), "Sucesso teste.");
if (data === 'L') {
window.location.href = "verdelandia.html";
}
},
error: function () {
navigator.notification.alert("Estamos verificando o problema.", fn_ErroApp(), "Ocorreu um problema.");
}
});
}
If someone have any idea of how to solve that, i would stay really grateful. Thank you everyone with try to help.
I did couple things in your ajax configuration:
Removed contentType: "application/json" because you sending only query string. By default contentType is application/x-www-form-urlencoded; charset=UTF-8.
Instead to manually configure query string parameter I added as data option.
I added parameters in error handler and you will be able to inspect which error you have.
Please see how it looks in your case:
$.ajax({
type: "GET",
url: linkServidor + "api/GuardaUsuario/GetConsultaLogUsu",
data: {
'uuid': uuid
},
success: function(data) {
navigator.notification.alert(data, fn_ErroApp(), "Sucesso teste.");
if (data === 'L') {
window.location.href = "verdelandia.html";
}
},
error: function(xhr, ajaxOptions, thrownError) {
navigator.notification.alert("Estamos verificando o problema.", fn_ErroApp(), "Ocorreu um problema.");
}
});
Instead to creating URL as string you can try to use action helper:
#Url.Action("actionName", "controllerName", new { uuid= "<uuid>" })
I'm creating my own filter. The filter has a dropdownlist, when this dropdownlist changes jquery will make an ajaxcall to the corresponding HTTPPOST - controller action. In this action I filter the list and pass it through to my view.
Once the list has reached my view, the webgrid is not updating. Here is some code with some debug information to show what's happening.
Controller
normal action
public ActionResult Projects()
{
IEnumerable<Project> projects = Adapter.ProjectRepository.Get();
int test = projects.Count();
List<ProjectsDisplayViewmodel> projectsView = new List<ProjectsDisplayViewmodel>();
string strCats = "";
foreach (Project prj in projects)
{
strCats = "";
Mapper.CreateMap<Project, ProjectsDisplayViewmodel>();
ProjectsDisplayViewmodel newProject = Mapper.Map<Project, ProjectsDisplayViewmodel>(prj);
foreach (Category cat in prj.Categories)
{
strCats += cat.CategoryName + ", ";
}
newProject.strCategories = strCats;
projectsView.Add(newProject);
}
ViewBag.Categories = new SelectList(Adapter.CategoryRepository.Get(), "CategoryID", "CategoryName");
/*projectsview contains 4 projects now*/
return View(projectsView);
}
httppost action
[HttpPost]
public ActionResult Projects(string catID, string strSearch)
{
IEnumerable<Project> projects = Adapter.ProjectRepository
.Get()
.Where(x =>
x.Categories.Any(
c =>
c.CategoryID == Convert.ToInt16(19))
);
int test = projects.Count();
List<ProjectsDisplayViewmodel> projectsView = new List<ProjectsDisplayViewmodel>();
string strCats = "";
foreach (Project prj in projects)
{
strCats = "";
Mapper.CreateMap<Project, ProjectsDisplayViewmodel>();
ProjectsDisplayViewmodel newProject = Mapper.Map<Project, ProjectsDisplayViewmodel>(prj);
foreach (Category cat in prj.Categories)
{
strCats += cat.CategoryName + ", ";
}
newProject.strCategories = strCats;
projectsView.Add(newProject);
}
ViewBag.Categories = new SelectList(Adapter.CategoryRepository.Get(), "CategoryID", "CategoryName");
/*projectsview contains 1 project now AND WILL DISPLAY 4*/
return View(projectsView);
}
project.cshtml
#model IEnumerable<Freelauncher.Models.ProjectsDisplayViewmodel>
#{
ViewBag.Title = "Projects";
}
#{
var grid = new WebGrid(Model, canPage: true, rowsPerPage: 25,
selectionFieldName: "selectedRow",ajaxUpdateContainerId: "gridContent");
grid.Pager(WebGridPagerModes.NextPrevious);
}
<h2>Alle projecten</h2>
#Html.DropDownList("Categories", (SelectList) ViewBag.Categories)
<div id="gridContent">
#grid.GetHtml(
columns: grid.Columns(
grid.Column("ProjectTitle", "Titel"),
grid.Column("ProjectDeadlineDate", "project deadline"),
grid.Column("ProjectEndRegisterDate", "Registreer deadline"),
grid.Column("ProjectBudget", "Prijs"),
grid.Column("ProjectIsFixedPrice", "Vaste prijs"),
grid.Column("strCategories","Categorieën"),
grid.Column("ProjectID", "meer info", format: (item) => Html.ActionLink("info", "project", new { Id = item.ProjectID} ))
//grid.Column("ProjectID", "meer info", format: Html.ActionLink("info", "project", new { Id = }
))
</div>
What am I missing that the project list in my view is not updated, the correct data is passed to the view....
edit
The ajax call
$("#Categories").change(function () {
var param = $(this).val();
$.ajax({
type: "POST",
url: "/Project/Projects",
data: { catID: $(this).val(), strSearch: 'test' },
dataType: "json",
success: function (response) { console.log("succes"); },
error: function (xhr, ajaxOptions, thrownError) {console.log("error"); }
});
});
I just noticed that nothing is printed in my console.log.... Not the success neither the error function.
You don't seem to be doing anything in the success callback of your AJAX request (other than a console.log call). So it's perfectly normal that nothing updates. You need to manually update your DOM if you want this to happen.
So you should modify your HttpPost controller action so that it returns a PartialView containing the grid. And then in your success callback inject the newly received partial into the DOM:
success: function (response) {
$('#some_id_of_a_containing_div').html(response);
console.log("succes");
},
In this example you should wrap the partial view into a containing div which will get updated here:
<div id="some_id_of_a_containing_div">
#Html.Partial("Partial_Containing_Your_Grid")
</div>
I wanna make twitter like microblog site which other users can follow my posts.
For that i made page with all currently registered users. In front of each name there is button to follow/unfollow user. (Like in Twitter)
View -
#{
ViewBag.Title = "Users";
}
#model MembershipUserCollection
#foreach (MembershipUser item in Model)
{
if(User.Identity.Name != item.UserName)
{
<li>#item.UserName
<span id="sp-#item.UserName"><input id="#item.UserName" name="submit" type="submit" value="Follow" class="follow-user fg-button ui-state-default"/></span>
</li>
}
}
<script type="text/javascript">
$(".follow-user").live("click", function (e) {
e.preventDefault();
var data = $(this).attr("id");
var spid = '#sp-' + data;
var btnid = '#' + data;
var val = $(this).attr('value');
$.ajax({
type: "POST",
url: "User/FollowUser",
data: { id: data },
cache: false,
dataType: "json",
success: function () {
if (val == 'Follow') {
$(btnid).attr('value', 'Unfollow');
}
else {
$(btnid).attr('value', 'Follow');
}
}
});
});
</script>
Controller -
public ActionResult Index()
{
return View(Membership.GetAllUsers());
}
public void FollowUser(string id)
{
ViewData["test"] = "test";
var n = FollowingUser.CreateFollowingUser(0);
n.FollowingId = id;
n.FollowerId = User.Identity.Name;
string message = string.Empty;
var list = new List<FollowingUser>();
list = (from a in db.FollowingUsers where a.FollowerId == User.Identity.Name && a.FollowingId == id select a).ToList();
if (list.Count() == 0)
{
try
{
db.AddToFollowingUsers(n);
db.SaveChanges();
}
catch (Exception ex)
{
message = ex.Message;
}
}
else
{
db.DeleteObject((from a in db.FollowingUsers where a.FollowerId == User.Identity.Name select a).FirstOrDefault());
db.SaveChanges();
}
}
FollowingUsers Table -
Now i wanna change button status on page load checking database whether he is already followed or not.
Ex- If user already followed it should display like below.
When you show this view to a user where this button is displayed, Load the status also, if the person is following or not.
public ActionResult Index()
{
var model = new MemberShipViewModel();
//We check here if the logged in user is already following the user being viewd
foreach(var member in Membership.GetAllUsers())
{
var user = (from a in db.FollowingUsers where a.FollowerId == User.Identity.Name && a.FollowingId == member.UserName select a).FirstOrDefault();
model.Members.Add(new Member{UserName = member.UserName,IsFollowing=user!=null});
}
//This line will remove the logged in user.
model.Members.Remove(model.Members.First(m=>m.UserName==User.Identity.Name));
return view(model);
}
In your index view model, you need to make some changes.
#model MemberShipViewModel
#foreach (var item in Model)
{
<li>#item.UserName
if(!item.IsFollowing)
{
<span id="sp-#item.UserName"><input id="#item.UserName" name="submit" type="submit" value="Follow" class="follow-user fg-button ui-state-default"/></span>
}
else
{
<span id="sp-#item.UserName"><input id="#item.UserName" name="submit" type="submit" value="Follow" class="unfollow-user fg-button ui-state-default"/></span>
}
</li>
}
$(".follow-user").live("click", function (e) {
e.preventDefault();
var data = $(this).attr("id");
var spid = '#sp-' + data;
var btnid = '#' + data;
var val = $(this).attr('value');
$.ajax({
type: "POST",
url: "User/FollowUser",
data: { id: data },
cache: false,
dataType: "json",
success: function () {
if (val == 'Follow') {
$(btnid).attr('value', 'Unfollow');
}
else {
$(btnid).attr('value', 'Follow');
}
}
});
});
You need to write some javascript now. Nobody is going to write full software for you.
Seems you are missing very basic programming skills.
cheers