Reputation: 475
I have 3 divs" NewAction NewController NewArea
I have an $.Ajax post with the url currently as follows '@Url.Action("CurrentAction", "CurrentController", new { area = "CurrentArea" })'
I have several pages that require this particular Ajax post so I put the Ajax post in a partial, and each main page that uses it, has a parameter in the partial call, eg:
@Html.Partial("_PartialPage", new [] { "NewAction", "NewController", "NewArea" })
The divs in #1 above are successfully populated dynamically with the string values in #3
Despite many efforts & attempts, I cannot change the @Url.Action values in #2 to the values in the divs in #1.
I even tried to declare C# private variables and populate them with the foreach that populated the divs above and pass those values to the @Url.Action link, but I get a run error.
Does anyone know a way I can pass the parameter values in my partial call (#3) to the Url.Action method in the Ajax post in #2 above.
Thanks in Advance.
Upvotes: 0
Views: 2293
Reputation: 1039508
You could have a method that will extract the values that are passed to this strongly typed partial and build the url:
@model string[]
@functions {
public string GetUrl() {
if (Model != null && Model.Length > 2)
{
var values = new RouteValueDictionary();
values["controller"] = Model[0];
values["action"] = Model[1];
values["area"] = Model[2];
return Url.RouteUrl(values);
}
return Url.Action("CurrentAction", "CurrentController", new { area = "CurrentArea" });
}
}
<script type="text/javascript">
var url = @Html.Raw(Json.Encode(GetUrl()));
$.ajax({
url: url,
type: 'POST',
success: function(result) {
// ...
}
});
</script>
will render like this:
<script type="text/javascript">
var url = "/NewArea/NewAction/NewController";
$.ajax({
url: url,
type: 'POST',
success: function(result) {
// ...
}
});
</script>
But if you don't need those route values separately another possibility is to directly pass the entire url to the partial view:
@Html.Partial("_About", Url.Action("NewAction", "NewController", new { area = "NewArea" }))
and then inside the partial simply use it:
@model string
<script type="text/javascript">
var url = @Html.Raw(Json.Encode(Model));
$.ajax({
url: url,
type: 'POST',
success: function(result) {
// ...
}
});
</script>
Upvotes: 2