I´m new to mvc and I try to to do a simple Ajax call to my controller, so I can use a date- and timepickers in my create view.
I get this error message when I use debugging in IE, but if I do a breakpoint it looks like I got correct data.
The parameters dictionary contains a null entry for parameter 'Lokal' of non-nullable type 'System.Int32' for method
'System.Web.Mvc.ActionResult CreateEvent(System.String, System.String,
System.String, Int32)' in
'VLVision.Controllers.SammantradesAdminController'. An optional
parameter must be a reference type, a nullable type, or be declared as
an optional parameter.Parameternamn: parameters
HTML
script type="text/javascript">
function createSammantrade() {
var sammantrade = document.getElementById('sammantrade').value;
var date = document.getElementById('datepicker').value;
var startTime = date + ' ' + document.getElementById('StartTimepicker').value;
var endTime = date + ' ' + document.getElementById('EndTimepicker').value;
var lokal = document.getElementById('lokal').value;
$.ajax({
url: "#Url.Action("CreateEvent", "SammantradesAdmin")",
data: { createSammantrade: sammantrade, createStartTime: startTime, createEndTime: endTime, createLokal: lokal },
type: "POST",
error: function () {
alert("An error occurred.");
},
success: function (data) {
$("#clanderDiv").html(data);
$("#setEventResponse").html("Händelse sparad");
// $(".blank").tooltip();
}
});
}
Controller
public ActionResult Create()
{
ViewBag.lID = new SelectList(db.Lokal, "lID", "lLokal");
return View();
}
[HttpPost]
public ActionResult CreateEvent(string createSammantrade, string createStartTime, string createEndTime, int Lokal)
{
Sammantrade sammantrade = new Sammantrade();
sammantrade.sSammantrade = createSammantrade;
sammantrade.sStartTid = Convert.ToDateTime(createStartTime);
sammantrade.sSlutTid = Convert.ToDateTime(createEndTime);
sammantrade.lID = Lokal;
if (ModelState.IsValid)
{
db.Sammantrade.Add(sammantrade);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.lID = new SelectList(db.Lokal, "lID", "lLokal", sammantrade.lID);
return View(sammantrade);
}
Since you have different names for the parameter in JS and in C#, it cannot be bound:
data: { createSammantrade: sammantrade, createStartTime: startTime, createEndTime: endTime, createLokal: lokal }
public ActionResult CreateEvent(string createSammantrade, string createStartTime, string createEndTime, int Lokal)
Either change createLokal to lokal in JS or do vice versa in C# (or bind one name to another).
Your parameter name in json is different from the c# action, these two should match. Change one of those:
either change createLokal : lokal to Lokal:lokal or in your action change parameter name to createLokal in your action
Thanks, it did not work at first. But when I debugged it I saw that the result from lokal was a string I change it to a string and then convert it back to a int.
Now I have some other problems, but I think I can fix the rest.
Sry for my crappy English, but I hope you understand what I mean.
Thanks!
Related
I'm trying to code a simple autocomplete using LINQ to entities and Razor (new to c# sharp as well) and i'm having trouble displaying json data in my view.
My controller is as follows:
public ActionResult AutoCompleteCity(string guess)
{
List<City> listData = null;
if (!string.IsNullOrEmpty(guess))
{
listData = db.AutoCompleteCity(guess);
}
return Json(new { Data = listData });
}
AJAX call:
function getCities(input) {
var serviceURL = $("#autocompleteURL").val();
var url =
$.ajax({
type: "POST",
url: serviceURL,
data: {
'guess': input
},
dataType: 'json',
success: function (response) {
if (response.Data != null) {
if ($("#targetUL") != undefined) {
$("#targetUL").remove();
}
Data = response.Data;
$.each(Data, function (i, value) {
$("#targetUL").append($("<li class='targetLI' onclick='javascript:agregarTexto(this)'>" + JSON.stringify(value) + "</li>"));
});
});
}
I might be missing a bracket or two :D
Any way when i retrieve records from the database and try to pass JSON values to the view the output is:
{"Data":[{"Selected":false,"Text":null,"Value":null}]}
I assume I'm not passing the JSON listData correctly. Any input will be greatly appreciated, thanks!
EDIT: here is a screencap of the values returned by listData in my controller
This is my LINQ query
public List<City> AutoCompleteCity(string guess)
{
using (var context = new Sports.SportsEntities())
{
var query = (from loc in context.city
join prov in context.state on loc.STATE_ID equals prov.STATE_ID
where loc.CITY_DESC.Contains(guess.ToUpper())
select new
{
city = loc.CITY_DESC,
state = prov.STATE_DESC,
});
IEnumerable<City> cityList= from ba in query.AsEnumerable()
select new City(ba.city, ba.state);
return cityList.ToList();
}
}
This error:
{"Data":[{"Selected":false,"Text":null,"Value":null}]}
was caused by having declared private attributes in the City Class, or by failing to declare getter/setter methods if said attributes are meant to be private.
I figured that out by looking at the screen capture posted on my question, only displaying the "selected", "text" and "value" properties and not the city and state description in the query results, which was what I needed to display below the textbox input.
This controller method will do the trick:
public JsonResult AutoCompleteCity(string term)
{
List<City> listData = new List<City>();
if (!string.IsNullOrEmpty(term))
{
listData = db.AutoCompleteCity(term);
}
return Json(listData, JsonRequestBehavior.AllowGet);
}
The problem is probably this piece of code in the AJAX call:
if ($("#targetUL") != undefined) {
$("#targetUL").remove();
}
By doing this you are removing the ul tag from the DOM and therefore cannot add the li elements you are constructing in this piece of code:
$.each(Data, function (i, value) {
$("#targetUL").append($("<li class='targetLI' onclick='javascript:agregarTexto(this)'>" + JSON.stringify(value) + "</li>"));
});
If you want to clear the list use .empty():
if ($("#targetUL") != undefined) {
$("#targetUL").empty();
}
if you want to return a JSON, change that:
public ActionResult AutoCompleteCity(string guess)
by
public JsonResult AutoCompleteCity(string guess)
and also try that:
Data = JSON.parse(response.Data);
It looks like your method returns a list of City objects, so maybe you need to use the property of that objects to get to the city name, something like this:
$.each(Data, function (i, city) {
$("#targetUL").append($("<li class='targetLI' onclick='javascript:agregarTexto(this)'>" + city.Name + "</li>"));
});
I have a drop down list that I need to fill with datetime values passed from an ajax call. The values that populate look like this: "/date1234847269/" and not actual dates. I just need the dates to be passed into the drop down list. I do not need the time stamps that are also in the datetime value that is returned from the controller.
I'm not sure if jQuery has issues with handling c# datetime values and not strings. Any help would be appreciated. Thanks
My View:
<select id="ddlDate" class="form-control bold">
<option value='0'>--Select Date--</option>
</select>
My Ajax Call:
function loadDateDDL(historicalIsChecked, monthlyIsChecked) {
$.ajax({
type: 'POST',
url: '#Url.Action("GetGroupReportDates")',
dataType: 'json',
data: { isMonthly: monthlyIsChecked },
success: function (returnData) {
convertDate(returnData);
$("#ddlDate").empty();
$("#ddlDate").append("<option value='0'>--Select Date--</option>");
$.each(returnData, function (value, key) {
$("#ddlDate").append($("<option></option>")
.attr("value", value).text(key));
});
//alert(returnData);
},
error: function (ex) {
alert('Failed to retrieve dates.' + ex);
}
});
}
function convertDate(returnData)
{
var date = new Date(returnData);
return date;
}
My Controller:
public JsonResult GetGroupReportDates ( Boolean isMonthly )
{
List<DateTime> reportDates = RealmsModel.RealmsAuditDataInterface ( ).GetGroupQueryRptDates ( isMonthly );
return new JsonResult ( )
{
Data = reportDates,
MaxJsonLength = Int32.MaxValue
};
}
Update 1/21/2016:
I am now passing my json data "returnData" to the javascript function below and converting it based on another stack post: How do I format a Microsoft JSON date?
function convertDate(returnData)
{
var date = new Date(returnData);
return date;
}
This now gives me the error "date = Invalid Date {}, returnData = ["/Date(1451628000000)/"]". I feel like I'm getting close. Any help is appreciated.
I resolved this with the following:
function convertDate(returnData)
{
var pattern = /Date\(([^)]+)\)/;
var results = pattern.exec(returnData);
var dt = new Date(parseFloat(results[1]));
return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
}
The format you're seeing is the old "microsoft" way of formatting dates. There are 2 ways to get around it.
One way would be to use the JSON.Net serialiser instead of the built in JavaScriptSerializer, as it (since version 4.5) formats dates so that they can be automatically parsed.
Another (quicker) way would simply be to extract the numbers from the date in it's current format as pass them to a new javascript Date object.
function toDate(value) {
return new Date(parseInt(/Date\(([^)]+)\)/.exec(value)[1], 10));
}
I'm trying to use Url.Action to call the controller c# function:
public ActionResult Setup(string ID, string Definition)
This function is located in the controller class MachineController.cs, and it returns a PartialView.
So, in with my script, i'm trying to call function 'Setup' with the line:
var selected = $('#dropselector').find(':selected').text();
$.get('#Url.Action("Setup", "Machine", new { ID = #Model.ID , Definition = "_holder"})'.replace("_holder", selected), function (data) {
$('#MachineSetup').replaceWith(data);
});
What seems to happen is the first parameter (ID) is passed no problem, but the second parameter (Definition) is always empty string. I've even tried assigning 'Definition' to #Model.ID same as the ID field as they are both strings, but it just seems to result in the same, ID is populated but Definition is an empty string.
The problem definitely relates to the passing of a second parameter, any ideas?
you could try the following
var selected = $('#dropselector').find(':selected').text();
$.get(
'#Url.Action("Setup","Machine", new { ID = #Model.ID })',
{
data:{definition:selected}
} ,
function (data)
{
$('#MachineSetup').replaceWith(data);
});
as the url will contain the Model.ID but the dynamic value of selected will change.
also if you are doing a Setup would you not consider a POST action to make sure the values are not cached on the client machine.
I'm using $.post() to post an array of integer values to my controller.
Here's how I construct my array:
var ratings = [];
$('#ratings input[name=newReviewRatings]').each(function () {
ratings.push($(this).val());
});
Here's how I'm posting it to the controller:
$.post('#Url.Action("CreateReview", "Provider")',
{
id: providerId,
ratings: ratings,
comment: comment
});
Here's the form data that gets posted:
{id=437baf29-4196-4966-88de-a8fde87ef68d&ratings%5b%5d=1&ratings%5b%5d=2&ratings%5b%5d=3&ratings%5b%5d=4&ratings%5b%5d=5&comment=Comments}
And here's my controller signature:
public ActionResult CreateReview(Guid id, int[] ratings, string comment)
{
// ....
}
That seems like that should be right, but ratings is always null. Can anyone see what I'm missing?
I also tried string[] ratings and got the same result. I also saw a suggestion to pass the array using JSON.stringify(ratings) but that didn't seem to help either.
In adition to converting the post data to json, you can also set the traditional param to true. This will cause jQuery to use the correct post format for MVC.
jQuery.ajaxSettings.traditional = true;
$.post('#Url.Action("CreateReview", "Home")',
{
id: 'GUID STRING HERE',
ratings: [1, 2, 3],
comment: 'adfef'
});
Try to specify contentType like this:
$.ajax({
url:url,
type:"POST",
data:data,
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(){
...
}
})
I use the jquery ui controls.
I have a datepicker and I retrieve the date as follows:
var sDate = $("#startDatePicker").datepicker('getDate');
var eDate = $("#endDatePicker").datepicker('getDate');
which as an example for sDate returns
Tue Aug 14 00:00:00 UTC+0200 2012
I call the code from the web page as follows
$.ajax(
{
url: '#Url.Action("LogsView","Home")',
type: 'POST',
data: { startDate: sDate, endDate: eDate },
success: function(result) { alert(result); },
error: function(param1) { alert(param1); }
});
I have a controller with the following action
public JsonResult LogsView(DateTime startDate, DateTime endDate)
{
var items = FetchItems(startDate, endDate);
return Json(items, JsonRequestBehavior.AllowGet);
}
When I run it, part of the error that is returned is as follows (when vied in fiddler):
The parameters dictionary contains a null entry for parameter 'startDate' of non-nullable type 'System.DateTime' for method 'System.Web.Mvc.JsonResult LogsView(System.DateTime, System.DateTime)' ..
I've check my params sent via fiddler and it is as follows startDate=&endDate=
Anyone know how to format and pass in the date correctly (I assume this is where the error lies)?
I needed to add .toJSON() to $("#startDatePicker").datepicker('getDate')
i.e. $("#startDatePicker").datepicker('getDate').toJSON()
if you get an error on the toJSON() function then try
var sd = $("#startDatePicker").datepicker('getDate');
var sDate = $.datepicker.formatDate('dd-MM-yy', sd);
You need to convert the date to string before you send it off to $.ajax() method.
You can this method to convert date to string:
function ShowUTCDate()
{
var dNow = new Date();
var utc = new Date(dNow.getTime() + dNow.getTimezoneOffset() * 60000);
var utcdate= (utc.getMonth()+1) + '/' + utc.getDate() + '/' + utc.getFullYear() + ' ' + utc.getHours() + ':' + utc.getMinutes();
return utcdate;
}