Nisar
Nisar

Reputation: 6038

AJAX error in routing asp.net mvc

I have a link to perform some ajex function.

  <td title="address/list" class="link">Addresses</td>
  <td title="email/list" class="link">Email</td>
  <td title="phone/list" class="link">Phone Numbers</td>
  <td title="contact/edit" class="link">Edit</td>
  <td title="contact/delete" class="link">Delete</td>

javascript code

 $('.link').live('click', function(event) {
    var id = $.trim($('td:first', $(this).parents('tr')).text());
    var loc = $(this).attr('title');
    console.log(loc);
    // check to ensure the link is not a delete link
    if (loc.lastIndexOf('delete') == -1) {
      $.get(loc + '/' + id, function(data) {
        $('#details').html(data);
      });
    // if it is, show the modal dialog   
    } else {
      $('#dialog').dialog({
        buttons: {
          'Confirm': function() {
            window.location.href = loc + '/' + id;
          },
          'Cancel': function() {
            $(this).dialog('close');
          }
        }
      }); 
      $('#dialog').dialog('open');
      }
    }); 

enter image description here

my routing is like

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default",
            "{controller}/{action}/{id}",
            new { controller = "Contact", action = "List", id = "" } 
        );
    }

Upvotes: 0

Views: 97

Answers (2)

codeandcloud
codeandcloud

Reputation: 55333

Do these things

Markup

<td title="/address/list" class="link">Addresses</td>

Suppose your controller is like this,

public class ContactController : Controller
{
    public JsonResult GetAddressesByID(int id)
    {
        var addresses = SomeMethodToFetchAddresses(id);
        return Json(addresses, JsonRequestBehavior.AllowGet);
    }
}

Now the routing should be like this.

routes.MapRoute(
    "GetAddressRoute", //Route name
    "address/list/{id}", // URL with parameters
    new { controller = "Contact", action = "GetAddressesByID", id = UrlParameter.Optional } // Parameter defaults
);

Upvotes: 1

Benoit
Benoit

Reputation: 1117

I guess you are in the dir contacts ... Use url.action like this:

<td data-url="@Url.Action("list", "email", new {id = item.id})" ...

Then get the url :

var url = $(this).data('url');

Upvotes: 1

Related Questions