简体   繁体   中英

MVC with Ajax call - not passing object to controller method

I have the following code in a simple MVC view:

<div id="CarText"><%=Model.Cars[10].Name %></div>
<div id="SelectedCar">no car selected</div>
<%=Ajax.ActionLink("ajax test","TestMethod",new {carObj = Model.Cars[10]},new AjaxOptions {UpdateTargetId = "SelectedCar"})%>

Then in my controller, I have the following:

public ActionResult TestMethod(Car carObj)
{
   return PartialView("SelectedCar", carObj);
}

When I run the page, it all renders as I expect (eg, the name of the 11th car is displayed in the first div. Then, when I click the link, the code in the controller is called, but the "carObj" parameter is always null.

I've read a fair few pages and blogs now and I'm failing to see what I've done wrong... hence this question.

Answers, as always, greatly appreciated :)

So it turns out you can't pass an object via an ActionLink... I suppose that makes sense when you think about it really.

Ho-hum.. guess I'm going to have to add an ID parameter simply so I can reference it via Ajax :/

i agree with sk93
and though i havent used asjax.actionlink method much(a jquery guy).
i can point out one problem with your solution in your action link method your are using {carObj = SOME_CAR_OBJ} this means what you are sending is an object with a property named carObj and some value .
what instead you should have is a JSON object

{
//all the car propertiese
name = cars[10].name,
id = cars[10].id
//etc etc
}

this way possibly you will be able to send the carObj back to the server

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM