Tuesday, March 1, 2011

Ajax.ActionLink, how to send the selected object in the partial view? asp.net mvc

I guess this is a noob question, but here it comes:

I have a list of products:

<% foreach (var item in Model) { %>

    <tr>
        <td>
            <%= Html.Encode(item.code) %>
        </td>
        <td>
            <%= Html.Encode(String.Format("{0:g}", item.date)) %>
        </td>
        <td>
            <%= Html.Encode(item.category) %>
        </td>
        <td>
            <%= Html.Encode(item.description) %>
        </td>
        <td>
            <%= Html.Encode(String.Format("{0:F}", item.price)) %>
        </td>
     ......
}

And a partial view after all of these (in the same page):

 <div id="productForEdit">
          <fieldset>
           <legend>Your Selected Product</legend>
           <% Html.RenderPartial("~/Views/Products/Edit", productObject); %>
          </fieldset>
    </div>

How do I use Ajax.ActionLink, so that when I will click the description of a product, the product will be plugged in the Partial View from the bottom of the page? I tried some combination with UpdateTargetId="productForEdit", but I had no success.

The purpose is to have a quick edit tool in the page.

From stackoverflow
  • I think this should work:

    <td>
      <%= Ajax.ActionLink(Html.Encode(item.description), /* link text */
                          "GetProduct", /* action name */
                          "Product", /* controller name */
                          new { productCode = Model.code }, /* route values */
                          new AjaxOptions() { InsertionMode = InsertionMode.Replace,
                                              UpdateTargetId = "productForEdit" }) %>
    </td>
    

    This does expect a ProductController with an action named GetProduct, which takes a parameter productCode. Have this action return the view "Products/Edit". You could also pass the whole product as a parameter to the action method, but that changes nothing to the basic idea. Good luck!

    Andrei T. Ursan : Your answer and this http://blog.goyello.com/2009/09/24/asp-net-mvc-issue-with-ajax-actionlink/ solved my problem. Thank you!

0 comments:

Post a Comment