1

I am trying to call a method inside a controller in MVC from a javascript action. The javascript action is supposed to invoke this method inside the controller and send some parameters to it.

My Javascript code looks like this:

location.href = '@Url.Content("~/Areas/MyArea/MyMethod/"+Model.MyId)';

My Method is defined as follows:

[HttpGet] 
public ActionResult MyMethod(int? MyId) 
{ 
   doSomething(MyId); 
   return View("MyView"); 
}

However, when i debug the application, when the method is called the MyId parameter is passed as null and not as the current value of the MyId parameter in my model. What can I do to correctly send or retrieve this value? Thanks!

1 Answer 1

2

In your route definition I suppose that the parameter is called {id} and not {MyId}:

public override void RegisterArea(AreaRegistrationContext context) 
{
    context.MapRoute(
        "MyArea_default",
        "MyArea/{controller}/{action}/{id}",
        new { action = "Index", id = UrlParameter.Optional }
    );
}

So try to be more consistent and adapt your controller action parameter name accordingly:

[HttpGet] 
public ActionResult MyMethod(int? id) 
{ 
    doSomething(id); 
    return View("MyView");
}

Also you probably wanna use url helpers instead of hardcoding some url patterns in your javascript code:

window.location.href = '@Url.Action("MyMethod", "SomeControllerName", new { area = "MyArea", id = Model.MyId })';

The Url.Content helper is used to reference static resources in your site such as javascript, css and image files. For controller actions it's much better to use the Url.Action helper method.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.