I have a Create ActionMethod, something along the lines of:
[AcceptVerbs(HttpVerbs.Post)]
public ActionMethod Create(Journey journey)
{
if (Request.IsAjaxRequest())
{
//Save values
return Json(new { JourneyID = journey.JourneyID } );
}
}
The Journey object that I pass in is from my LINQ2SQL datamodel. I call the above ActionMethod from my Javascript using the JQuery.Post function, like:
var journeyData = {
CustomerID: $('#CustomerID').val(),
JourneyID: $('#JourneyID').val(),
EstimatedTravelTime: $('#EstimatedTravelTime').val(),
RouteName: $('#RouteName').val(),
.....
};
$.post('/Journey/Create',
journeyData,
function(jsonResult) {
//deal with result
},
'json'
);
The issue that I am having is that in the ActionMethod Journey.RouteName is always returning as null but the JSON that I pass back has a value, I check this using
alert(JSON.stringify(journeyData));
and in the resultant JSON object RouteName has a value, e.g. 'Go to work'. Any ideas why this wouldn't be being set in the ActionMethod? All other values that I pass back are being set fine.
Just a try and error suggestion:
First thing i would try is to rename "RouteName" param with somethign different, as "RouteName" is also a property of some MVC-redirect methods..
Have you examined your request JSON object that's going to the server?
Have you tried adding quotes to your string property value?
Like this:
var journeyData = {
CustomerID: $('#CustomerID').val(),
JourneyID: $('#JourneyID').val(),
EstimatedTravelTime: $('#EstimatedTravelTime').val(),
RouteName: '"' + $('#RouteName').val() + '"',
.....
};
There are a couple of things to consider. I'm guessing this is already in place, but your model must have a getter and setter on the RouteName property in order to be properly bound. Another thought is you might not be establishing the strong binding. This is usually done as part of the view's page declaration (e.g. Inherits="System.Web.Mvc.ViewPage") but I'm not sure this is happening prior to your post.
Related
I have 2 examples below:
#Html.ActionLink("Create New", "Create", new { id = Model.Id })
and,
return RedirectToAction("Index", new { id = review.RestaurantId });
My question is regarding the new { id = xxx} part in object route values. Why do we use "new" in this case? What exactly does it do? Does it initialize "id" variable in this case?
Also, it is strange that these methods, create and index definition can only take arguments as defined in the route values...
That is,
public ActionResult create { int id)
{ ...}
is correct but following is wrong....
public ActionResult create { int somethingelse)
{ ...}
So please tell me what is the new {id = xx} in my first 2 examples is doing?
Thanks
new {} creates a new object of type Object. The type is anonymous. You see that syntax when writing linq queries that end in " select new {x = "foo". y="bar"}". It is often used when setting an object to type "var".
What you are doing in your ActionLink is providing Route Values. MVC takes the properties and values in the object and puts them in the QueryString of the request. It is what you might refer to as "magic". You can set a break point in your controller Action and check "HttpContext.Request.QueryString" to see it.
The input values for you Action methods have to match the properties that are being passed in via the QueryString.
That is actually creating an anonymously typed object and passing it into ActionLink(). ActionLink then uses that object, coupled with your routing rules to generate the link. MVC will look for properties on that object that match the routing names (usually of route parameters) and figure out how to build it. Since you likely have the default MVC route (/controller/action/{id}) that is what links everything together.
Further, that is why id "is correct", but somethingelse "is wrong".
If you change "id" to "somethingelse" in your routing rule, you could then see new { soemthingelse = ""} work in your ActionLink().
Does that help?
In both cases your creating a new anonymous object to pass into the query string as a route value. You create a new object because one does not already exist on the view.
The MVC source code:
if (additionalViewData != null) {
foreach (KeyValuePair<string, object> kvp in new RouteValueDictionary(additionalViewData)) {
viewData[kvp.Key] = kvp.Value;
}
}
They use it to create new RouteValueDictionary parameters.
You don't have to use it the this manor. You could create an object on the model and pass it in:
public class SomeModel
{
public SomeModel()
{
MyObject = new { id = 10 };
}
public int Id {get;set;}
public object MyObject {get;set;}
}
#Html.ActionLink("Create New", "Create", Model.MyObject)
This would also work though is probably not something you would attempt.
For the second part of your question. The RouteValueDictionary searches by key and assigns the value to the key that was given.
So whatever you call the key in the anonymous object, MVC will attempt to assign the value to it on the action. The name must match or they key cannot assign the value.
I am able to successfully call Backbone's HTTP POST and PUT methods and have them link up to my server using Asp.Net MVC.
The problem is that when I call the HTTP DELETE using model.destroy() I get this error...
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Delete(Int32)' in 'GSASF.Controllers.AdminController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
Right before I call model.destroy() I logged the id to the console and it was correct. This is my code. *Note that my model doesn't have a field called id but instead a field called HoverId. The database table already existed so I have to make due.
Delete: function(id) {
if (id) {
for (var i = this.collection.length - 1; i >= 0; i--) {
var item = this.collection.at(i);
if (item.get("HoverId") == id)
alert("Item to be destroyed ID: " + item.get("id"));
item.destroy();
};
}
[ActionName("SpaceToolTipEdit")]
[HttpDelete]
public ActionResult Delete(int id)
{
var imageHover = sr.GetImageHoverById(id);
if (imageHover != null)
{
sr.DeleteImageHover(imageHover);
return new HttpStatusCodeResult(200);
}
return new EmptyResult();
}
Ok, I feel dumb now.
The solution was all to simple. I had originally set the url attribute to my /{Controller}/{SpaceToolTipEdit} url. I was supposed to set this to the urlRoot attribute instead.
I'm having troubles reading a Json result back from a controller method...
I have this method in my controller:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult GetCurrent()
{
IList<string> profile = new List<string>();
profile.Add("-1");
profile.Add("Test");
profile.Add("");
return this.Json(profile);
}
And it is being called by this jquery ajax post:
$.post("/Profile/GetCurrent", function(profile) { profileCompleteOpen(profile); }, "json");
and the javascript function called on the post's callback:
function profileCompleteOpen(profile) {
alert(profile);
alert(profile[0]);
}
The result of the first alert shows the array like this:
["-1","Test",""]
But the result of the second alert shows this:
[
rather than
-1
What am I doing wrong here... I've compared it to one of the other times I'm doing this and it seems to be the exact same. Why isn't it recognizing it's an array?
Thanks,
Matt
Try converting the json data in profile to a proper object by using eval() on it.
Example:
var profileObject = eval('(' + profile + ')');
Hmmm, I'd be doing what you're trying to do a little differently.
I'd either return a fully qualified object and then use it's properties;
class MyObj
{
public string name{get;set;}
}
fill the object and return it as a json object. then you're jquery code can access like any other object.
The other way might be to do a return PartialView("MyView", model);
That will return the partial view as html back to your page which you can then append to your html.
I think the type of profile is string instead of array. Why? Check the $.post method parameters. Maybe the problem is there.
$.post("url", null, function(profile) { ... }, "json");
When I use:
new AjaxOptions
{
UpdateTargetId = "VoteCount" + indx,
OnSuccess = "AnimateVoteMessage"
}
everything works fine...but I am trying to animate items in a list, with automatically assigned ID's. Since I want each of these to be addressable from my javascript, I believe I need to pass a parameter to my javascript. But when I use:
new AjaxOptions
{
UpdateTargetId = "VoteCount" + indx,
OnSuccess = "AnimateVoteMessage(2)"
}
I get an " Sys.ArgumentUndefinedException: Value cannot be undefined." exception. Well I get that when using the debug versions of MicrosoftMvcAjax.js. When using the compressed version I get a "Microsoft JScript runtime error: 'b' is null or not an object"
So my question is, can I pass a parameter to my javascript function using the OnSuccess event for a ActionLink?
Is this the right approach? How else am I going to have one javascript function have the ability to be run on 10 items (in my case the IDs of multiple DIVs) on my page?
There is a better way to do this - use the built in parameters that the OnSuccess call can be expected to pass
the built in parameters (the ones I found so far anyway) are data, status and xhr
data = whatever you return from the action method
status = if successful this status is just a string that says "success"
xhr = object that points to a bunch of javascript stuff that I will not be discussing...
so you would define your javascript like this (you can leave out the arguments you don't need - since all we want is our data back from the action we will just take the data argument)
function myOnSuccessFunction (data)
{
..do stuff here with the passed in data...
}
like I said before, data is whatever JSON that may be returned by the ActionResult so if your controller action method looks like this...
public ActionResult MyServerAction(Guid modelId)
{
MyModel mod = new MyModel(modelId);
mod.DoStuff();
return Json(mod, JsonRequestBehavior.AllowGet);
}
you would set up your action link like this...
#Ajax.ActionLink("Do Stuff", "MyServerAction", new { modelId = Model.Id }, new AjaxOptions { OnSuccess = "mySuccessScript(data);", OnFailure = "myFailureScript();", Confirm = "Are you sure you want to do stuff on the server?" })
this will create a confirmation message box asking if you want to actually invoke the action - clicking yes on the prompt will invoke the call to the controller - when the call comes back - the data argument will contain a JSON object of whatever you returned in your action method. Easy Peasy!
But wait! What if I want to pass another custom argument?! Simple! Just add your arguments to the front of the list...
instead of this...
function myOnSuccessFunction (data)
{
..do stuff here with the passed in data...
}
do this (you can have more than one custom argument if you like, just keep adding them as needed)...
function myOnSuccessFunction (myCustomArg, data)
{
..do stuff here with the passed in data and custom args...
}
then in your setup - just get the argument through some client side script within your ActionLink definition... i.e.
#Ajax.ActionLink("DoStuff", "MyServerAction", new { modelId = Model.Id }, new AjaxOptions { OnSuccess = "mySuccessScript(myClientSideArg, data);", OnFailure = "myFailureScript();", Confirm = "Are you sure you want to do stuff on the server?" })
Note that "myClientSideArg" in the OnSuccess parameter can come from wherever you need it to - just replace this text with what you need.
Hope That Helps!
or...a bit different syntax that worked for me:
OnSuccess = "( function() { MyFunction(arg1,arg2); } )"
There is a better way, which I believe is how Microsoft intended it: Set the AjaxOptions.OnSuccess to a function pointer, i.e. just the name of the function, no parameters. MVC will send it parameters automagically. Below is an example.
JScript parameter:
public class ObjectForJScript
{
List<int> Ids { get; set; }
}
Jscript function:
function onFormSuccess(foobar){
alert(foobar);
alert(foobar.Ids);
alert(foobar.Ids[0]);
}
View code:
#using (Ajax.BeginForm("ControllerAction", "ControllerName",
new AjaxOptions
{
OnSuccess = "onFormSuccess" //see, just the name of our function
}))
{
#Html.Hidden("test", 2)
}
Controller code:
public JsonResult ControllerAction(int test)
{
var returnObject = new ObjectForJScript
{
Ids = new List<int>{test}
};
return Json(returnObject);
}
Note that the parameter name in the JScript function doesn't matter, you don't have to call it "returnObject" even though the controller names it so.
Also note that Json() conveniently turns our List into a JScript array. As long as the methods of the C# object are translatable to Json, you can call them in the JScript like I've done.
Finally, the controller doesn't have to return a JsonResult, it can be ActionResult (but it's usually better to have a controller action do just one thing).
The above example will alert two objects (the Json and the array object which it contains), and then 2.
You can simply do this
Razor:
... OnSuccess = "AnimateVoteMessage('" + YourParameter + "')"
Please note the single quotes!
JavaScript:
function AnimateVoteMessage(YourParameter){
alert(YourParameter);
}
Enjoy,
Try this - it works for me:
OnSuccess = "new Function('MyFunction(" + myParameter + ")')"
Use this:
OnSuccess = "function(){yourfunction(" + productcode + ");}"
or
OnSuccess = "function(){yourfunction(this, " + productcode + ");}"
I ran in this issue too... and did not find a way to solve it!
I did a workaround (which is not nice but solved it for now... maybe until someone posts a solution here)...
what I did was place a hidden field in the TargetId div and OnSuccess I called a js method which retrieves the value from the hidden field <- this could happen in your AnimateVoteMessage method ...
See http://www.codeproject.com/KB/ajax/Parameters-OnSuccess.aspx
Basically:
function yourCallBack(arg1,arg2) {
return function(result) { // Your old function
alert(arg1); // param will be accessible here
alert(arg2); // param will be accessible here
alert(result);// result = the response returned from Ajax
}
}
Simply, at AjaxOptions, use the following:
OnSuccess = "onSuccessFunction(data, 'Arg1');"
Then at your function, you will get the new value as:
function onSuccessFunction(result, myNewArg) {
//Prints Arg1
Console.Write(myNewArg)
}
I have a complex JSON object which is sent to the View without any issues (as shown below) but I cannot work out how Serialize this data back to a .NET object when it is passed back to the controller through an AJAX call. Details of the various parts are below.
var ObjectA = {
"Name": 1,
"Starting": new Date(1221644506800),
"Timeline": [
{
"StartTime": new Date(1221644506800),
"GoesFor": 200
}
,
{
"StartTime": new Date(1221644506800),
"GoesFor": 100
}
]
};
I am not sure how this object can be passed to a Controller Method, I have this method below where the Timelines object mirrors the above JS object using Properties.
public JsonResult Save(Timelines person)
The jQuery I am using is:
var encoded = $.toJSON(SessionSchedule);
$.ajax({
url: "/Timeline/Save",
type: "POST",
dataType: 'json',
data: encoded,
contentType: "application/json; charset=utf-8",
beforeSend: function() { $("#saveStatus").html("Saving").show(); },
success: function(result) {
alert(result.Result);
$("#saveStatus").html(result.Result).show();
}
});
I have seen this question which is similar, but not quite the same as I am not using a forms to manipulate the data.
How to pass complex type using json to ASP.NET MVC controller
I have also seen references to using a 'JsonFilter' to manually deserialize the JSON, but was wondering if there is a way to do it nativly though ASP.NET MVC? Or what are the best practices for passing data in this way?
Edit:
This method should no longer be needed with the arrival of MVC 3, as it will be handled automatically - http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx
You can use this ObjectFilter:
public class ObjectFilter : ActionFilterAttribute {
public string Param { get; set; }
public Type RootType { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext) {
if ((filterContext.HttpContext.Request.ContentType ?? string.Empty).Contains("application/json")) {
object o =
new DataContractJsonSerializer(RootType).ReadObject(filterContext.HttpContext.Request.InputStream);
filterContext.ActionParameters[Param] = o;
}
}
}
You can then apply it to your controller methods like so:
[ObjectFilter(Param = "postdata", RootType = typeof(ObjectToSerializeTo))]
public JsonResult ControllerMethod(ObjectToSerializeTo postdata) { ... }
So basically, if the content type of the post is "application/json" this will spring into action and will map the values to the object of type you specify.
You say "I am not using a forms to manipulate the data." But you are doing a POST. Therefore, you are, in fact, using a form, even if it's empty.
$.ajax's dataType tells jQuery what type the server will return, not what you are passing. POST can only pass a form. jQuery will convert data to key/value pairs and pass it as a query string. From the docs:
Data to be sent to the server. It is
converted to a query string, if not
already a string. It's appended to the
url for GET-requests. See processData
option to prevent this automatic
processing. Object must be Key/Value
pairs. If value is an Array, jQuery
serializes multiple values with same
key i.e. {foo:["bar1", "bar2"]}
becomes '&foo=bar1&foo=bar2'.
Therefore:
You aren't passing JSON to the server. You're passing JSON to jQuery.
Model binding happens in the same way it happens in any other case.
A different take with a simple jQuery plugin
Even though answers to this question are long overdue, but I'm still posting a nice solution that I came with some time ago and makes it really simple to send complex JSON to Asp.net MVC controller actions so they are model bound to whatever strong type parameters.
This plugin supports dates just as well, so they get converted to their DateTime counterpart without a problem.
You can find all the details in my blog post where I examine the problem and provide code necessary to accomplish this.
All you have to do is to use this plugin on the client side. An Ajax request would look like this:
$.ajax({
type: "POST",
url: "SomeURL",
data: $.toDictionary(yourComplexJSONobject),
success: function() { ... },
error: function() { ... }
});
But this is just part of the whole problem. Now we are able to post complex JSON back to server, but since it will be model bound to a complex type that may have validation attributes on properties things may fail at that point. I've got a solution for it as well. My solution takes advantage of jQuery Ajax functionality where results can be successful or erroneous (just as shown in the upper code). So when validation would fail, error function would get called as it's supposed to be.
There is the JavaScriptSerializer class you can use too. That will let you deserialize the json to a .NET object. There's a generic Deserialize<T>, though you will need the .NET object to have a similar signature as the javascript one. Additionally there is also a DeserializeObject method that just makes a plain object. You can then use reflection to get at the properties you need.
If your controller takes a FormCollection, and you didn't add anything else to the data the json should be in form[0]:
public ActionResult Save(FormCollection forms) {
string json = forms[0];
// do your thing here.
}
This answer is a follow up to DaRKoN_'s answer that utilized the object filter:
[ObjectFilter(Param = "postdata", RootType = typeof(ObjectToSerializeTo))]
public JsonResult ControllerMethod(ObjectToSerializeTo postdata) { ... }
I was having a problem figuring out how to send multiple parameters to an action method and have one of them be the json object and the other be a plain string. I'm new to MVC and I had just forgotten that I already solved this problem with non-ajaxed views.
What I would do if I needed, say, two different objects on a view. I would create a ViewModel class. So say I needed the person object and the address object, I would do the following:
public class SomeViewModel()
{
public Person Person { get; set; }
public Address Address { get; set; }
}
Then I would bind the view to SomeViewModel. You can do the same thing with JSON.
[ObjectFilter(Param = "jsonViewModel", RootType = typeof(JsonViewModel))] // Don't forget to add the object filter class in DaRKoN_'s answer.
public JsonResult doJsonStuff(JsonViewModel jsonViewModel)
{
Person p = jsonViewModel.Person;
Address a = jsonViewModel.Address;
// Do stuff
jsonViewModel.Person = p;
jsonViewModel.Address = a;
return Json(jsonViewModel);
}
Then in the view you can use a simple call with JQuery like this:
var json = {
Person: { Name: "John Doe", Sex: "Male", Age: 23 },
Address: { Street: "123 fk st.", City: "Redmond", State: "Washington" }
};
$.ajax({
url: 'home/doJsonStuff',
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(json), //You'll need to reference json2.js
success: function (response)
{
var person = response.Person;
var address = response.Address;
}
});
in response to Dan's comment above:
I am using this method to implement
the same thing, but for some reason I
am getting an exception on the
ReadObject method: "Expecting element
'root' from namespace ''.. Encountered
'None' with name '', namespace ''."
Any ideas why? – Dan Appleyard Apr 6
'10 at 17:57
I had the same problem (MVC 3 build 3.0.11209.0), and the post below solved it for me. Basically the json serializer is trying to read a stream which is not at the beginning, so repositioning the stream to 0 'fixed' it...
http://nali.org/asp-net-mvc-expecting-element-root-from-namespace-encountered-none-with-name-namespace/