I'm trying to use JQuery UI Autocomplete on a text box to filter through a Paged List and dynamically update the list so it only shows anything that starts with the value from the filter. However whenever I start typing into the search box I get the following error:
Syntax Error: Unexpected Token <
Here's my controller:
[HttpGet]
public ActionResult Index(string filter, int currentPage = 1)
{
List<string> allEmails = null;
if (!string.IsNullOrEmpty(filter))
{
allEmails = dataContext.Emails
.Where(x => x.email.StartsWith(filter))
.Select(x => x.email)
.ToList();
}
else
{
allEmails = dataContext.Emails
.Select(x => x.email)
.ToList();
}
PagedList<string> model = new PagedList<string>(allEmails, page, pageSize);
ViewBag.Emails = allEmails.OrderBy(x => x).Skip((page - 1) * pageSize).Take(pageSize);
ViewBag.Filter = filter;
return View(model);
}
Here's My view:
#model PagedList<string>
#using PagedList
#using PagedList.Mvc
<div id="paginatedDiv">
<table id="pageinatedTable">
<tr>
<th>
Email
</th>
</tr>
#foreach (var item in ViewBag.Emails)
{
<tr>
<td>
#item
</td>
</tr>
}
</table>
#Html.PagedListPager(Model,
(page) => Url.Action("Index", "Home", new
{
page,
pageSize = Model.PageSize,
filter = ViewBag.Filter
}),
PagedListRenderOptions.ClassicPlusFirstAndLast)
</div>
#Html.TextBox("search")
#section scripts
{
<script type="text/javascript">
$(document).ready(function () {
$('#search').autocomplete({
source: function(request, response)
{
$.ajax({
url: '#Url.Action("Index", "Home")',
dataType: "json",
contentType: 'application/json, charset=utf-8',
data: {
filter : $("#search").val(),
page : '#Model.PageNumber'
},
error: function (xhr, status, error) {
alert(error);
}
})},
minlength: 1
});
});
</script>
}
Is what I'm trying to do here possible? Am I going about it the wrong way? If you need more information let me know.
The Ajax function is returning a HTML error which is trying to getting parsed to the function. It will fail and error out because the first character will be '<' like
Related
I have a problem that I was stacked on for a while. I am rather new to this stuff so please be patient. I think it is like very simple to solve but I am running circles now. My intention is to make a simple alert that informs that method was completed. As you can see below my first attempt was made with simple string and if statement. I dont want to reload the page any more but now I have a problem that method ends later than alert script starts.
So I have a controller:
[HttpPost]
public ActionResult Executor(LMCMainViewModel model)
{
var curlsExecutor = _curls;
var applicationPurgeCurl = curlsExecutor.GetApplicationCurl(model);
var temporary = model.SuccessExecutionStatus = curlsExecutor.CurlCaller(model.ApplicationList.ApplicationCurl);
var tempListOfApplications = PopulateModel(model);
model.ApplicationList.ListOfApplications = tempListOfApplications.ApplicationList.ListOfApplications;
model.SuccessExecutionStatus = temporary;
return View("ListOfApplications", model);
}
And I have my view:
#model LMC.Models.LMCMainViewModel
#{
ViewData["Title"] = "Liberation";
}
#using (Html.BeginForm("HeaderString", "LMC"))
{
}
#using (Html.BeginForm("Executor", "LMC", FormMethod.Post))
{
<div class="col-sm-2" asp-action="ListOfApplications">
#Html.DropDownListFor(x => x.ApplicationList.ChosenApplication, Model.ApplicationList.ApplicationListItem, new { #id = "DropdownID" })
</div>
<div class="col-sm-2 col-sm-push-5">
#Html.HiddenFor(x => x.ApplicationList.ApplicationListItem)
<input class="btn ctn-success" id="submit" type="submit" value="Submit" />
<button id="submitButtonAjax" type="button" class="btn btn-success">Ajax button</button>
<div class="col-sm-12">
#Html.Label(null, (Model.SuccessExecutionStatus ? "Success" : " "),
new { Style = Model.SuccessExecutionStatus ? "color: green;" : "color: red;" })
</div>
</div>
}
Than I tried to implement many variations of Ajax script but I got so twisted that I can't even post you the best one... One thing I know is that when I remove: #using (Html.BeginForm("Executor", "LMC", FormMethod.Post)) and try to place it into Ajax it simply doesn't work. My intention is to have something that would work like this:
<script type="text/javascript">
$("#submitButtonAjax").on("click", function () {
$.ajax({
type: 'POST',
url: "/LMC/Executor",
success: function () {
alert("Went well");
}
});
</script>
I tried to convert controller method return into Json but it didnt work as well. I would appreciate any advices, where I can read about anything similar(I am aware that there are probably many similar topics, but I wan't able to implement anything that was working into my code, because I find my question one step backwards in comparison to others), or maybe it is that easy and I am missing something and you can just post a solution. Anyway, many thanks for any help.
The ajax call should look like bellow
$( document ).ready(function() {
$("#submitButtonAjax").on("click", function () {
var postData = {
FirstPropertyOfTheModel: ValueForTheFirstProperty,
SecondPropertyOfTheModel: ValueForTheSecondProperty,
};
$.ajax({
type: 'POST',
url: "/LMC/Executor",
data:postData,
success: function () {
alert("Went well");
},
error: function () {
alert("Opssss not working");
}
});
});
});
data is the value for the model of ActionResult method of the controller. The FirstPropertyOfTheModel and SecondPropertyOfTheModel will be replaced by the name of property and assign the corresponding value respectably. At url you can use
'#Url.Action("Executor", "LMC")'
so the ajax will look like
$( document ).ready(function() {
$("#submitButtonAjax").on("click", function () {
var postData = {
FirstPropertyOfTheModel: ValueForTheFirstProperty,
SecondPropertyOfTheModel: ValueForTheSecondProperty,
};
$.ajax({
type: 'POST',
url: '#Url.Action("Executor", "LMC")',
data:postData,
success: function () {
alert("Went well");
},
error: function () {
alert("Opssss not working");
}
});
});
});
Currently I have a main view called getRolesByYear.cshtml. In this view I have three buttons, each for an year. When I click a button(or on page load) I invoke a method, which takes an int 'year' for a parameter and calls an ajax with the year parameter. This ajax calls an action method (getRolesByYear, the one for the main view). The Action method makes a query to a database, a result of which is a list of ViewModel objects. In the return statement I return a PartialView like this : return PartialView("_yearlyRoles",list);. Sadly, after all this, instead of getting a list of the desired objects in my frontend, all i get is an error from the error part of the ajax call. I am generally a novice and I am very stuck with this.
Here is the main view getRolesByYear.cshtml:
#{
ViewBag.Title = "getRolesByYear";
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
getRolesForYear(parseInt(#DateTime.Now.Year));
$(function () {
$('#years a').click(function () {
var year = $(this).text();
console.log(year);
getRolesForYear(parseInt(year));
});
})
//console.log(year);
function getRolesForYear(year) {
console.log(year);
$.ajax({
type: "POST",
url: '#Url.Action("getRolesByYear", "WorkRoles")',
dataType: "json",
data: {
year: year
},
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
$("#partial").html(data);
}
function errorFunc() {
alert('error');
}
}
</script>
<div id = "years" class="btn-group btn-group-justified timeline">
#DateTime.Now.Year
#DateTime.Now.AddYears(-1).Year
#DateTime.Now.AddYears(-2).Year
</div>
<div id = "partial"></div>
The partial view :
#model IEnumerable<eksp.Models.RoleViewModel>
#foreach (var item in Model)
{
<div class="jumbotron">
<h2>item.Role.RoleName</h2>
<h1> item.Role.RoleDescription</h1>
<p class="lead">Focus start : item.Role.FocusStart</p>
<p>Focus end : item.Role.FocusStart </p>
</div>
}
The Action Method :
[HttpPost]
public ActionResult getRolesByYear(int year)
{
string currentUserId = User.Identity.GetUserId();
var list = db.WorkRoles.
Join(db.WorkRolesUsersDetails,
o => o.WorkRoleId, od => od.WorkRoleId,
(o, od) => new
{
WorkRoleId = o.WorkRoleId,
RoleName = o.RoleName,
RoleDescription = o.RoleDescription,
CompanyId = o.CompanyId,
WRUDId = od.WRUDId,
UserDetailsId = od.UserDetailsId,
FocusStart = od.FocusStart,
FocusEnd = od.FocusEnd
}).ToList()
.Select(item => new RoleViewModel(
item.WorkRoleId,
item.RoleName,
item.RoleDescription,
item.CompanyId,
item.WRUDId,
item.UserDetailsId,
item.FocusStart,
item.FocusEnd)).ToList();
//RoleViewModel rv = list;
if (Request.IsAjaxRequest())
{
return PartialView("_yearlyRoles", list);
}
else
{
return View(list);
}
}
Given the reported error message, you need to alter your ajax call. By setting "data" parameter to "json" you're telling ajax to expect JSON-formatted data back in the response, but a partial view is HTML, so change your ajax call to reflect this:
$.ajax({
type: "POST",
url: '#Url.Action("getRolesByYear", "WorkRoles")/' + year,
dataType: "html", //set the correct data type for the response
success: successFunc,
error: errorFunc
});
As an aside, you can improve your error handling on the client side quite straightforwardly by changing errorFunc to something like this, using the parameters that are provided to the callback by $.ajax:
function errorFunc(jQXHR, textStatus, errorThrown) {
alert("An error occurred while trying to contact the server: " + jQXHR.status + " " + textStatus + " " + errorThrown);
}
For less instrusive reporting and/or easier debugging, you could change the alert to console.log. To get more detail you could also log the entire jQXHR object:
console.log(JSON.stringify(jQXHR));
I am working on cascaded dropdownlist with data passed with dataview.
Controller:
public ActionResult Index()
{
ViewBag.States = new SelectList(db.PLStates, "PLStateID", "PLStateName");
ViewBag.Cities = new SelectList(db.PLCitys, "PLCityID", "PLCityName");
return View();
}
[HttpPost]
public JsonResult GetCity(int SelectedStateId)
{
SelectList result = new SelectList(db.PLCitys.Where(x => x.PLStateID == 3), "PLCityID", "PLCityName");
return Json(result);
//return Json(ViewBag.Cities = new SelectList(db.PLCitys.Where(x => x.PLStateID == 3), "PLCityID", "PLCityName"));
}
HTML:
<script type="text/javascript">
$(document).ready(function () {
$("#States").change(function () {
var SelCity1 = $("#States").val();
$("#Cities").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetCity")',
dataType: 'JSON',
data: { SelectedStateId: SelCity1 },
success: function (Cities) {
ViewBag.Cities = Cities;
$("#Cities").append('Cities');
alert("success" + Cities);
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>
<div>
#Html.DropDownList("States", "Select one")
#Html.DropDownList("Cities", "Select one")
</div>
In alert i can see the json gives back objects but the Cities dropdownlist becomes emptied with no value inside. Why ddl.cities is not filled with retured values??
Additional question is how to add style to dropdownlist??
You will have to manually add options to the cities drop down via js with the Json data returned from the controller.
As far as styling. You can style in inline by adding a "style"= to the html attributes or style with external css class using the #class html attribute.
I am having a hard time figuring out how to get cascading drop down lists to work for my asp.net mvc3 application. I have a popup box and I would like to display 2 dropdownlists, the 2nd being populated based on what is selected in the first. Each time I run the application the controller method returns the correct list of values, but instead of hitting the success part of the ajax call I hit the error part. I have done lots of research and followed several examples I have found but something is still not quite right, any help would be greatly appreciated.
Edit:
Further inspection using firebug shows an error 500 internal server error which states: Exception Details: System.InvalidOperationException: A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.GameEdition
I have the following jQuery / AJAX:
<script type="text/javascript">
$(function () {
$("#PlatformDropDownList").change(function () {
var gameId = '#Model.GameID';
var platformId = $(this).val();
// and send it as AJAX request to the newly created action
$.ajax({
url: '#Url.Action("Editions")',
type: 'GET',
data: { gameId: gameId, platformId: platformId },
cache: 'false',
success: function (result) {
$('#EditionDropDownList').empty();
// when the AJAX succeeds refresh the ddl container with
// the partial HTML returned by the PopulatePurchaseGameLists controller action
$.each(result, function (result) {
$('#EditionDropDownList').append(
$('<option/>')
.attr('value', this.EditionID)
.text(this.EditionName)
);
});
},
error: function (result) {
alert('An Error has occurred');
}
});
});
});
Here is my controller method:
public JsonResult Editions(Guid platformId, Guid gameId)
{
//IEnumerable<GameEdition> editions = GameQuery.GetGameEditionsByGameAndGamePlatform(gameId, platformId);
var editions = ugdb.Games.Find(gameId).GameEditions.Where(e => e.PlatformID == platformId).ToArray<GameEdition>();
return Json(editions, JsonRequestBehavior.AllowGet);
}
Here is my web form html:
<div id="PurchaseGame">
#using (Html.BeginForm())
{
#Html.ValidationSummary(true, "Please correct the errors and try again.")
<div>
<fieldset>
<legend></legend>
<p>Select the platform you would like to purchase the game for and the version of the game you would like to purchase.</p>
<div class="editor-label">
#Html.LabelFor(model => model.PlatformID, "Game Platform")
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.PlatformID, new SelectList(Model.Platforms, "GamePlatformID", "GamePlatformName"), new { id = "PlatformDropDownList", name="PlatformDropDownList" })
</div>
<div class="editor-label">
#Html.LabelFor(model => model.EditionID, "Game Edition")
</div>
<div id="EditionDropDownListContainer">
#Html.DropDownListFor(model => model.EditionID, new SelectList(Model.Editions, "EditionID", "EditionName"), new { id = "EditionDropDownList", name = "EditionDropDownList" })
</div>
#Html.HiddenFor(model => model.GameID)
#Html.HiddenFor(model => model.Platforms)
<p>
<input type="submit" name="submitButton" value="Purchase Game" />
<input type="submit" name="submitButton" value="Cancel" />
</p>
</fieldset>
</div>
}
You cannot send JSON encoded requests using the GET verb. So replace type: 'GET' with type: 'POST' and it will work. Also since you have specified a JSON request you must, well, send a JSON request which is achieved with the JSON.stringify function: data: JSON.stringify({ gameId: gameId, platformId: platformId }),. But since you only have 2 values I think that using GET would be easier. So my recommendation is to remove the contentType: 'application/json' parameter and have your AJAX request look like this:
$.ajax({
url: '#Url.Action("Editions")',
type: 'GET',
data: { gameId: gameId, platformId: platformId },
cache: 'false',
success: function (result) {
$('#EditionDropDownList').empty();
// when the AJAX succeeds refresh the ddl container with
// the partial HTML returned by the PopulatePurchaseGameLists controller action
if(result.length > 0)
{
$.each(result, function (result) {
$('#EditionDropDownList').append(
$('<option/>')
.attr('value', this.EditionID)
.text(this.EditionName)
);
});
}
else
{
$('#EditionDropDownList').append(
$('<option/>')
.attr('value', "")
.text("No edition found for this game")
);
}
},
error: function () {
alert('An Error has occured');
}
});
Also in the DropDownListFor helper in your Razor markup I notice the following:
onchange = "Model.PlatformID = this.value;"
All I can say is that this doesn't do what you might think it does.
UPDATE:
It seems that you are getting a circular object reference error because you are passing your editions domain model to the Json method. Circular reference object hierarchies cannot be JSON serialized. Besides you don't need to waste the bandwidth by sending all the crap contained in this editions to the client. All your client needs is a collection of ids and names. So simply use view models:
public ActionResult Editions(Guid platformId, Guid gameId)
{
var editions = ugdb
.Games
.Find(gameId)
.GameEditions
.Where(e => e.PlatformID == platformId)
.ToArray<GameEdition>()
.Select(x => new
{
EditionID = x.EditionID,
EditionName = x.EditionName
})
.ToArray();
return Json(editions, JsonRequestBehavior.AllowGet);
}
Hi I'm trying to refresh a mvccontrib grid, using ajax in MVC but it doesn't work. When I use "return PartialView("myview", mylist);" nothing happend. The response never came to the jquery code. I put the keyword debbuger to see if it works but never got there.
this is my JQuery Code to refresh the grid:
function refreshTable() {
$.ajaxSetup({
async: false,
cache: false
});
$.get('<%= Url.Action("RefreshGridData", "Countries") %>',
function (response) {
debugger;
$(".table-list").replaceWith(response)
});
}
And this is my Action:
public ActionResult RefreshGridData()
{
GetAllCountries();//this puts a list in the ViewData
return PartialView("CountriesPage", (List<iCatalogData.Country>)ViewData["CountriesList"]);
}
And this is my grid:
<div id="container">
<% Html.Grid((List<iCatalogData.Country>)ViewData["CountriesList"])
.Columns(column =>
{
column.For(co => Html.ActionLink(co.IdCountry.ToString(), "EditCountry", "Countries", new { id = co.IdCountry }, null)).Named("Id Country");
column.For(co => co.CountryName);
column.For(co => Html.ActionLink("Delete", "DeleteCountry", "Countries", new { id = co.IdCountry }, null)).Named("Delete");
}).Attributes(id => "example", #class => "table-list", style => "width: 100%;").Empty("No countries available").Render();
%>
</div>
Thanks.
I had a similar problem and solved it by changing the return type of the action to PartialViewResult instead of ActionResult. Could possibly be the same issue for you.