Reputation: 559
I'm getting an error that my Action Method was not found, but can't figure out what's wrong. I searched the internet now for hours but haven't found a solution till now.
In my View I have a JavaScript function:
<script type="text/javascript"> function ShowHideAds(button) { var dAds = document.getElementById("dAds"); if (dAds.style.display == "none") { dAds.style.display = "block" var txtBox = "Visible"; $.post('@Html.Action("GetState","Rights")', { txtAds: txtBox }); } else { dAds.style.display = "none" var txtBox = "Hidden"; $.post('@Html.Action("GetState", "Rights")', { txtAds: txtBox }); } } </script>
I'm switching between a Textbox and a Listbox and depending on which is visible, I want to pass the parameter to my method.
My method in my Controller is the following:
[HttpPost, ActionName("GetState")]
public ActionResult GetState(string txtAds, string txtRg)
{
if (txtAds != null)
stateTxtAds = txtAds;
if (txtRg != null)
stateTxtRg = txtRg;
return View();
}
and finally here is my routing:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Before using the @Html.Action() method I had following line of code:
$.post("/Rights/GetState", { txtAds: txtBox });
but this did not work when the project was deployed so I tried to use the @Html.Action two send my variables to my controller method.
Can anyone help please?
Thank you!
Upvotes: 0
Views: 203
Reputation: 2300
GetState(string txtAds, string txtRg)
has two parameters but you are only providing one. If you want it to accept two but only provide it one like you are doing in the call, do the following.
For example for the post @Html.Action("GetState", "Rights")', { txtAds: txtBox }
:
GetState(string txtAds, string txtRg = "")
This way you can just send txtAds
if you want and it should reach it.
The ajax I would recommend:
var json = '{txtAds: "' + txtAds + '"}'
$.ajax({
url:'@Url.Action("GetState", "Rights")',
type:'POST',
data: json,
contentType: 'Application/json',
success: function(result){
// Whatever you want to do next.
}
})
Upvotes: 1