Ajax loading Mvc Content Error - javascript

I know, there are several questions with near the same problem. But i cant figure it out, where my mistake is.
So at first my situation:
I'll load my content with ajax and push it to the site.
$.ajax({
url: _this.url,
contentType: "application/html; charset=utf-8",
type: "GET",
dataType: "html",
data: {
stamp: Date.now()
},
success: function (result) {
_this.app = $("<div id='" + _this.frameId + "' />")
.addClass("place-top-left page")
.css({
"height": "100%",
"z-index": 4000
})
.append($(result))
.appendTo(document.body);
if (loadedCallback) {
loadedCallback();
}
},
error: function (xhr, status) {
alert(xhr.responseText);
}
});
My controller:
public ActionResult Edit(int id)
{
var howToContent = Manager.Get(id);
var howToModel = new HowToModel()
{
MediaID = howToContent.Media.ID,
HowToTitle = howToContent.Title,
Name = howToContent.Name,
BusinessIds = howToContent.BusinessIDs.Select(it => it.ToString()).ToArray()
};
return View(howToModel);
}
And my View:
#model Hsetu.Help.Web.Areas.System.Models.HowTo.HowToModel
#{
ViewBag.Title = "Leitfaden bearbeiten";
Layout = "~/Areas/System/Views/Shared/AppSite.cshtml";
}
#section ScriptCSS{
#Scripts.Render("~/uploadScripts")
}
#using (Html.BeginForm())
{
<fieldset>
<label>
#Html.EditorFor(m => m.Name)
</label>
<label>
#Html.EditorFor(m => m.HowToTitle)
</label>
<label>
#Html.EditorFor(m => m.BusinessIds)
</label>
</fieldset>
}
The Error ill get is:
The model item passed into the dictionary is of type Hsetu.Help.Web.Areas.System.Models.HowTo.HowToModel, but this dictionary requires a model item of type System.Web.Mvc.MvcHtmlString
So it will step through the Controller and the View if i debug the code. I'll also get the right model and values!
Only the result on the success function from ajax is a json return with this error message.
This works for same code but without passing this howToModel into the view.
On the other side i found out, if ill use ajaxcall like this it will also work?! Sorry.. but WTF is the diffrence between this ajaxcalls?????
$.ajax({
url: _this.url,
contentType: 'application/html; charset=utf-8',
type: 'GET',
dataType: 'html',
data: {
stamp: Date.now()
}
})
.success(function (result) {
_this.app = $("<div id='" + _this.frameId + "' />")
.addClass("place-top-left page")
.css({
"height": "100%",
"z-index": 4000
})
.append($(result))
.appendTo(document.body);
if (loadedCallback) {
loadedCallback();
}
})
.error(function (xhr, status) {
alert(xhr.responseText);
});
So my question is, how can i get the first ajaxcall working? I need it with this syntax.. so there is no way around. And maybe someone can explain me the difference between the ajax. Doesnt find a really necessary reason!
Thanks

The difference between the ajax calls is that the .error() call on the returned object of the .ajax() call returns a deferred object, which is chainable, and allows multiple handlers to be set, whereas passing in an error: function can only be done once per ajax() call -- I believe that is an older syntax.
(BTW .error() is deprecated, and you should use .fail() instead -- if you were using that approach)
Regarding your MVC (server-side) error: this is often the kind of error message I get when I attempt to pass in an property value that is null into a strongly-typed helper. Check the values of .Name, .HowToTitle, and .BusinessIds for nulls.

Related

Data passing error from javascript to controller

I'm working on ASP.NET MVC project , I want to get location dropdown selected value and according to that i need to load values to City dropdown , i implemented following code and location dropdown onselect event call the javascript function and javascript function call the controller method but when executing controller method locationId is null ,and i debug javascript and locationID is there till the this line data: JSON.stringify({ locationId: +locationId }), after that javascript returns error.but controller method get hit but locationId null
code for dropddowns
<div class="row">
<div class="col-sm-4">
#Localizer["Locations"]
<select id="locationDropDown" class="selectpicker form-control" asp-for="selectedLocation" onchange="getCityList()">
<option value="0"><None></option>
#foreach (var item in Model.LocationList)
{
<option value="#item.Id">#item.Name</option>
}
</select>
</div>
</div>
<div class="row">
<div class="col-sm-4">
#Localizer["KioskGroup"]
<select id="cityDropDown" class="selectpicker form-control">
<option>---Select City---</option>
</select>
</div>
</div>
Javascript code
function getCityList()
{
debugger;
var locationId = $("#locationDropDown").val();
console.log(locationId)
$.ajax({
url: '/Kiosk/GetZoneListBYlocationID',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({ locationId: +locationId }),
success: function (result) {
$("#cityDropDown").html("");
$("#cityDropDown").append
($('<option></option>').val(null).html("---Select City---"));
$.each($.parseJSON(result), function (i, zone)
{ $("#cityDropDown").append($('<option></option>').val(zone.Id).html(zone.Name)) })
},
error: function(){alert("Whooaaa! Something went wrong..")},
});
controller method
public ActionResult GetZoneListBYlocationID(string locationID)
{
List<Zone> lstZone = new List<Zone>();
long locationId = long.Parse(locationID);
var zones = _zoneRepository.GetZonesByLocationId(locationId);
return Json(JsonConvert.SerializeObject(zones));
}
Your current code is sending the json string {"locationId":101} in the request body because you specified the contentType as application/json. This is useful when you want to send an object with multiple properties and your action method parameter is a DTO/POCO class type. Model binder will be reading from the request body and map it to the parameter.
In your case, all you are sending is a single value. So do not send the JSON string. simply create a js object and use that as the data attribute value. Also remove the contentType: application/json as we are not sending a complex js object as json string.
Also application/json is not a valid option for the dataType property. You may use json. But jQuery is smart enough to guess the value needed here from the response headers coming back from server. So you may remove it.
function getCityList() {
var locationId = $("#locationDropDown").val();
$.ajax({
url: '/Kiosk/GetZoneListBYlocationID',
type: 'POST',
data: { locationID: locationId },
success: function (result) {
console.log(result);
// populate dropdown
},
error: function () { alert("Whooaaa! Something went wrong..") },
});
}
Now this data will be send in Form Data as locationID=101 with Content-Type header value as application/x-www-form-urlencoded and will be properly mapped to your action method parameter.
You should use the correct types. In your action method, you are using string as your parameter and later trying to convert it to long. Why not use long as the parameter type ? Also if zones variable is a list of Zone object, you can pass that directly to the Json method. No need to create a string version in between.
public ActionResult GetZoneListBYlocationID(long locationId)
{
var zones = _zoneRepository.GetZonesByLocationId(locationId);
return Json(zones);
}
Why you are stringify the data.Below one should work without stringify
data: { locationId: +locationId },
I was facing the same problem. and after that, I have tried below solution.
Hope it will help you.
ajax call is as follows:
$.ajax({
type: 'POST',
url: "/Account/GetCities",
dataType: 'json',
data: { id: $("#StateID").val() },
success: function (states) {
$.each(states, function (i, state) {
$("#CityID").append('<option value="' + state.Value + '">' + state.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve cities.' + ex);
}
});
The controller code is as follows:
public List<CityModel> GetCities(int id)
{
//your code
}
You can do in your application like this:
function getCityList()
{
var locationId = $("#locationDropDown").val();
console.log(locationId)
$.ajax({
url: '/Kiosk/GetZoneListBYlocationID',
type: 'POST',
dataType: 'json',
data: { locationId: locationId },
success: function (result) {
$("#cityDropDown").html("");
$("#cityDropDown").append
($('<option></option>').val(null).html("---Select City---"));
$.each($.parseJSON(result), function (i, zone)
{ $("#cityDropDown").append($('<option></option>').val(zone.Id).html(zone.Name)) })
},
error: function(){alert("Whooaaa! Something went wrong..")},
});
}
And your controller will be same as you have done.

Calling [HTTPPost] from Javascript ASP.NET

I am using a method in my controller which imports data from an API. This method I am wanted to be called from two locations. First the view (currently working) and secondly a javascript function.
Start of controller method:
[ActionName("ImportRosters")]
[HttpPost]
public ActionResult PerformImportRosterData(int id, int? actualLength, int? rosterLength)
{
var authenticator = Authenticator(id);
var rosters = authenticator.Api().RosterData().ToDictionary(x => x.Id);
var databaseRosterDatas = SiteDatabase.DeputyRosterData.Where(x => x.SiteID == id)
.ToDictionary(x => x.Id);
Javascript Function:
$("#btnDeputyRunNowUpdate").click(function() {
$("#btnRunDeputyNow").modal("hide");
ActualLength = $("#actualRunLength").val();
RosterLength = $("#rosterRunLength").val();
$.ajax({
type: "POST",
url: "/deputy/PerformImportRosterData",
data: { SiteIDRoster, ActualLength, RosterLength }
});
SiteIDRoster = null;
location.reload();
$("#btnRunDeputyNow").modal("hide");
toast.show("Import Successful", 3000);
});
All values are being set but i am getting a 404 error on the url line
POST https://example.org/deputy/PerformImportRosterData 404 ()
I need a way to be able to call this c# method from both html and JS
This can be done if you will modify the URL in your AJAX. It should look something like
url: '<%= Url.Action("YourActionName", "YourControllerName") %>'
or
url: #Url.Action("YourActionName", "YourControllerName")
one more thing, I don't see if you do anything with the result of the call. your script does not have success part
success: function(data) {//do something with the return}
and would be very helpful to have error handler in your call.
full example on how AJAX should look like:
$.ajax({
url: "target.aspx",
type: "GET",
dataType: "html",
success: function (data, status, jqXHR) {
$("#container").html(data);
alert("Local success callback.");
},
error: function (jqXHR, status, err) {
alert("Local error callback.");
},
complete: function (jqXHR, status) {
alert("Local completion callback.");
}
})
For a good tutorial on AJAX read this document
Change after Comment:
my current code is below:
$("#btnDeputyRunNowUpdate").click(function() {
$("#btnRunDeputyNow").modal("hide");
ActualLength = $("#actualRunLength").val();
RosterLength = $("#rosterRunLength").val();
$.ajax({
type: "POST",
url: '<%= Url.Action("PerformImportRosterData", "DeputyController") %>',
data: { SiteIDRoster, ActualLength, RosterLength },
success: function(data) {
console.log(data);
console.log("TESTHERE");
}
});
}
UPDATE:
Noticed one more thing. Your parameters in the controller and AJAX do not match. Please try to replace your a few lines in your AJAX call with:
url: "/deputy/PerformImportRosterData",
data: { id: yourIDValue, actualLength: youractualLengthValue,
rosterLength :yourrosterLengthValue }
remember to set all variable values in javascript , if they have no values set them = to null.
Can you try copy paste code below
$.ajax({
type: "POST",
url: "/deputy/PerformImportRosterData",
data: { SiteIDRoster:999, ActualLength:1, RosterLength:2 }
});
And let me know if it wall cause any errors.
After attempting to solve for a few days, I created a workaround by creating two methods for importing the data. one for the httpPost and the second for import calling from javascript.
Not a great solution but it works. Thanks for your help Yuri

Autocomplete on Html.TextBox won't work

So, I've searched alot and went through alot of tutorials and even though I do everything exactly as in the tutorial, I just can't seem to get it working. Funny thing is, I have been involved in a project where we used the exact same solution and it worked.
I've got a textbox in my forum where users can search for threads in all categories where I am using ajax to show the result in a div in form of a partial view. This is working.
The problem is that I want the thread subjects that are containing the current search term to show up (in form of a normal string) while the user is typing, but I can't seem to get the implementation of autocomplete right. By the way I am retrieving my information from a MSSQL-database.
This is the javascript that I am using to autocomplete (which is not working) and below that you can see my Ajax-form that I use for the search (that works):
<link href="~/Content/jquery-ui.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-ui.min.js"></script>
#*Scripts for Ajax to show the partial view in the div with id "partialThreads" at request*#
<script src="~/Scripts/jquery-2.2.1.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script type="text/javascript">
$(function () {
$("#txtSearch").autocomplete({
source: '#Url.Action("GetThreadsBySearch", "Forum")'
});
});
</script>
#using (#Ajax.BeginForm("Threads", new AjaxOptions() { UpdateTargetId = "partialThreads", InsertionMode = InsertionMode.Replace, HttpMethod = "POST" }))
{
#Html.AntiForgeryToken()
<p><strong>Search for thread in all categories</strong></p>
#Html.TextBox("searchTerm", null, new { id = "txtSearch", style = "width: 1000px" })
<input type="submit" value="Search" />
}
Here is the div where I show the results of the search in form of a partial view:
<div id="partialThreads">
</div>
Here is the action method that I am using for my ajax-form search (the working one):
[HttpPost, ValidateAntiForgeryToken]
public ActionResult Threads(string searchTerm)
{
var model = string.IsNullOrWhiteSpace(searchTerm)
? new List<ThreadsListModel>()
: _threadRepo.GetThreadsBySearch(searchTerm).OrderByDescending(x => x.DateCreated).ToList();
return PartialView("_Threads", model);
}
And here is the method that I use to retrieve the information to my autocomplete (I've tried setting a break point on it, it doesn't even break):
public JsonResult GetThreadsBySearch(string term)
{
var threadNames = _threadRepo.GetThreadsBySearch(term).Select(x => x.Subject).ToList();
return Json(threadNames, JsonRequestBehavior.AllowGet);
}
Note that I use the same db-query to search with the form and for the autocomplete (only difference would be that I select the threadnames as a List in the GetThreadsBySearch method. So that can't be the problem (?). Here is query-method in case you want to have a look:
public ICollection<ThreadsListModel> GetThreadsBySearch(string subject)
{
using (var context = new ForumContext())
{
return
context.Threads.Where(x => x.Subject.ToLower().Contains(subject.ToLower()) && x.IsActive)
.Select(x => new ThreadsListModel()
{
ID = x.ID,
DateCreated = x.DateCreated,
CreatedBy = x.CreatedBy,
Subject = x.Subject,
PostsCount = x.Posts.Count
}).Distinct().ToList();
}
}
Also, I am using Visual Studio 2015 (.NET 4.5.2) MVC 5. I hope that I haven't forgot to write down any helpful information.
Your scripts are in the wrong order and jquery needs to be before jquery-ui (and also ensure that you do not have any duplicated scripts)
$("#MainContent_txtCountry").autocomplete({
source: function (request, response) {
var param = { keyword: $('#MainContent_txtCountry').val() };
$.ajax({
url: "Default.aspx/GetCountryNames",
data: JSON.stringify(param),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
});

ajax request not sending any data ASP.NET MVC project with jQuery

I'm fairly new to asp.net MVC but am baffled as to why my request isn't working.
I'm trying to send an ajax request with jquery as per:
jQuery(function ($) {
var total = 0,
share = $('div.share'),
googlePlusUrl = "https://plusone.google.com/_/+1/fastbutton?url=http://bookboon.com" + $(location).attr('pathname');
setTimeout(function() {
$.ajax({
type: 'GET',
data: "smelly",
traditional: true,
url: share.data('proxy'),
success: function(junk) {
//var $junk = junk.match(regex);
console.log(junk);
},
error: function (xhr, errorText) {
console.log('Error ' + xhr.responseType);
},
});
}, 4000);
And set a line in my RouteConfig as:
routes.MapRoute(null, "services/{site}/proxy", new { controller = "Recommendations", action = "Proxy" });
The markup has a data-attribute value as:
<div class="share" data-proxy="#Url.Action("Proxy", "Recommendations")">
And my Proxy action method starts with:
public ActionResult Proxy(string junk)
The problem is that the junk parameter is always null. I can see in the debug output that the route seems to correctly redirect to this method when the page loads (as per jQuery's document ready function), but I cannot seem to send any data.
I tried sending simple data ("smelly") but I don't receive that neither.
Any suggestions appreciated!
The model binder will be looking for a parameter in the request called junk, however you're sending only a plain string. Try this:
$.ajax({
type: 'GET',
data: { junk: "smelly" }, // <- note the object here
traditional: true,
url: share.data('proxy'),
success: function(junk) {
//var $junk = junk.match(regex);
console.log(junk);
},
error: function (xhr, errorText) {
console.log('Error ' + xhr.responseType);
},
});

MVC 4 APIController not receiving POST data

Sure this had been dealt with many times... but.. just cant see what im doing wrong!
This is a simple JS script that Posts data back to ApiController.
function WebCall(url,parameterObject, callBackFunction) {
this.callbackfunction = callBackFunction;
this.parameterObject = parameterObject;
this.url = url;
self = this;
this.GetData = function () {
//self = this;
$.ajax({
//dataType: "json",
type: "POST",
url: self.url,
data: JSON.stringify(self.parameterObject),
contentType: "application/json;charset=utf-8",
success: function (data) {
self.callbackfunction.call(this, data);
},//self.GotData,
error: function (xhRequest, ErrorText, thrownError)
{
alert("error : " + ErrorText)
},
complete: function () {},
})
}
}
The data being sent (parameterObject) is simply
var postData = {
clientId: id
}
The c# code in the controller is :
public class ClientPostObject
{
public string clientId;
}
public class ClientDetailController : ApiController
{
[HttpPost]
public ClientDetailWidgetData GetClient(ClientPostObject clientObject)
{
return new ClientModel().GetClientDetail(clientObject.clientId);
}
}
In Google chrome developer tools, the XHR is showinf 'form Data' as clientId:A0001 - so that looks ok?
No matter what I try (and I'be been through many suggestions on the web), the post data is not there.
Sure its something simple.... Thanks in advance.
Unless you're planning on using a full-on form to submit to this method at some other point, it doesn't really make sense to ask the model binder to attempt to bind to a complex type when you're just using one property. Change your method signature to:
[HttpPost]
public ClientDetailWidgetData GetClient(int clientId) // or whatever type clientId represents
{
return new ClientModel().GetClientDetail(clientId);
}
I'd also recommend adding Glimpse at some point (http://getglimpse.com/) so that you can see how the model binding and/or routing of your app works.
Try to ditch contentType and don't stringify data:
$.ajax({
type: "POST",
url: self.url,
data: self.parameterObject,
success: function (data) {...},
...
});

Categories

Resources