Passing data to controller using Ajax.ActionLink - c#

I am trying to write a link to a partial view on the same page. Everything works, except that I am not able to pass in the needed month parameter through my ajax.actionlink syntax. I've tried using the ViewDataDictionary, but to no avail. Also, RouteValueParameter was a thought I had, but I'm trying to pass a string, not an integer id.
Below is my code in the view, followed by the method in the controller:
<td>#Ajax.ActionLink("January", "ControllerMethod", new ViewDataDictionary{{"month", "January"}}, new AjaxOptions { UpdateTargetId = "view-month" })</td>
public ActionResult ViewMonths(string month)
{
//some code here
return PartialView("ViewMonths", schedule);
}
Any ideas?

Try this way
#Ajax.ActionLink("Link Text", "MyAction", "MyController", new { month = "January", plum = "2", moreparams = "U can do this all day"}, new AjaxOptions{ UpdateTargetId = "view-month" } )
Greatings

Related

ASP .NET MVC 5 - How to add form model inside Ajax.ActionLink?

I'm working on the table paging, where each page calls the controller to get part of the data, then return the partial view and update it into HTML table.
Here's my controller look like:
public ActionResult SearchData(FormModel model, int? page)
{
/*Codes to get data from DB*/
return PartialView("_DataTable", model);
}
The form input is something like this:
#model Project.ViewModel
#using (Ajax.BeginForm("SearchData", "Player", new AjaxOptions
{ HttpMethod = "GET", UpdateTargetId = "data-table", InsertionMode = InsertionMode.Replace }))
{
#Html.LabelFor(m => m.FormModel.Username)
#Html.TextBoxFor(m => m.FormModel.Username, new { placeholder = "[Username]" })
#*And some more input, all are in FormModel class.*#
}
<div id="data-table">
#Html.Partial("_DataTable")
</div>
The way I generate the page is as follows:
for (var pageNum = Model.PlayerList.Pager.StartPage; pageNum <= Model.PlayerList.Pager.EndPage; pageNum++)
{
if (pageNum == Model.PlayerList.Pager.CurrentPage)
{
<td><span>#pageNum</span></td>
}
else
{
<td>
#Ajax.ActionLink(pageNum.ToString(), "SearchData", new {page = pageNum}, new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "data-table"
})
</td>
}
}
I can only pass in the page value, is it possible to include the form input Model into Ajax.ActionLink? Something like this:
new {model = Model.FormModel, page = pageNum}
I tried the method above, but didn't work. Any help would be appreciated.
you need add properties of FormModel like this
new {Username="some username",page = pageNum}
I came out with another solution. I put the form model inside TempData just before the controller returns the partial view. At the beginning of the controller, I check if the page value is null, the form input should take from TempData instead. This way, we only pass in the page value since the form input model should always the same, using Ajax.ActionLink as I posted on the question.
Here's the code:
public ActionResult SearchData(FormModel model, int? page)
{
if (page != null)
{
model = TempData["FormModel"] as FormModel ?? new FormModel();
}
/*Codes to get data from DB*/
TempData["FormModel"] = model;
return PartialView("_DataTable", model);
}
do it like this and change fields names and values as your model
note: unfortunately, you should send each value one by one, but not the whole model
#Ajax.ActionLink(pageNum.ToString(), "SearchData",
new
{
FielNameInModel1= Model.FieldNameInModel,
FielNameInModel2 = "xyz",
FielNameInModel3 = 5,
FielNameInModel4 = pageNum.ToString(),
},
new AjaxOptions { HttpMethod = "GET", InsertionMode = InsertionMode.Replace, UpdateTargetId = "AllProjectsDiv", OnComplete = "AjaxFormCompleted" }
, new { #class = "className") })

ASP.NET MVC how to send param from #Ajax.ActionLink to method in controller

#Html.ActionLink((string)Model[i]["name"], "Info", "Home", new { uid = Model[i]["uid"].ToString() }, null)
[HttpGet]
public ActionResult Info(string uid)
{
TempData["uid"] = uid;
SearchModel model = new SearchModel();
List<DataTable> tables = model.GetUserInfo(uid);
TempData["tables"] = tables;
return View(model);
}
In the controller, there is a method that returns JsonResult. This method is used to obtain data, on the basis of which the js code will be executed.
public JsonResult GetCountryRisk(SearchModel model)
{
string uid = TempData["uid"].ToString();
IEnumerable<CountryRisk> list = new List<CountryRisk>();
list = model.GetCountryRisk(uid);
TempData["uid"] = uid;
return Json(list, JsonRequestBehavior.AllowGet);
}
The view has elements that simulate tabs and when clicked on the selected item, Ajax is called, which receives the data and passes it to the script.
<div id="tabHeadDiv">
<input type="button" value="Summary" class="tabControl" id="1" onclick="ShowOrHideTabs(this.id)" />
#Ajax.ActionLink("Relations", "Info", null, new AjaxOptions { Url = Url.Action("GetDataForGraph"), OnSuccess = "DrawGraph" }, new { #id = "2", #class = "tabControl" })
#Ajax.ActionLink("Map", "Info", null, new AjaxOptions { Url = Url.Action("GetCountryRisk"), OnSuccess = "drawRegionsMap" }, new { #id = "3", #class = "tabControl" })
</div>
Problem is that if a user opens several links in a new tab and wants to go to the tab, then on all tabs the result will be displayed, which was executed last.
So I want to understand if it's possible to send parameter to the GetCountryRisk method without using TempData ["uid"].
First, stop using a ViewBag or a TempData for uid. This is clearly a part of your state, and while these key-value stores have their uses, they are no good for your case.
Make uid a part of SearchModel, as it is obviously important for you as you handle search requests, and in Info action do this:
SearchModel model = new SearchModel();
model.UID = uid;
Now on the page I don't really understand why the Ajax.ActionLink mentions one controller/action pair and then uses another as the URL. Here is how I would imagine it:
#Ajax.ActionLink(
"Your controller name",
"GetCountryRisk",
new {uid = Model.UID},
new AjaxOptions {OnSuccess = "drawRegionsMap" },
new { #id = "3", #class = "tabControl" })
Finally in the GetCountryRisk action just use uid:
public JsonResult GetCountryRisk(SearchModel model)
{
string uid = model.UID;

MVC C# PagedList - PagedListPager passing parameters

I have a paged list using unobtrusive ajax that looks like this.
#Html.PagedListPager(Model, page => Url.Action("Images", "Admin", new { imageLibrary = image.ImageLibrary, page }),
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new AjaxOptions()
{ InsertionMode = InsertionMode.Replace, UpdateTargetId = "imagesContainer" }))
My controller looks like this:
public ActionResult Images(ImageModels image, int? page, string imageLibrary)
{
// do stuff here
}
I was trying to pass a model to my controller, so instead of imageLibrary = image.ImageLibrary, I should have only needed to pass image = imageModel, but when I pass the model itself, the controller gets a null value (yes the model name was spelled correctly). When I try to get a property of the model and pass it to the controller (that's the imageLibrary = image.ImageLibrary) the controller receives both the model and the imageLibrary string value! This works fine for the end result, I just don't understand why it works, and I shouldn't have to pass the string value imageLibrary to my controller - especially if I'm not really using it.
Any insight on this would be appreciated.

Updatating a span with Ajax.ActionLink

Hi I am trying to create a shopping cart using ajax.I am kind of stuck it's the first time I use ajax.What I am trying to do is create an ajax.Actiolink that will update a Inner text of a span tag.Here is my code so far:
//This is the span I want to update
<span id="UpdateCart">0</span>
#Ajax.ActionLink("Add To Cart" ,
"AddToCart" ,
"Products",
new {
ProductId = #products.ElementAt(0).Value
},
new AjaxOptions{
Url = "/Product/AddToCart",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "UpdateCart",
})
public ActionResult AddToCart(string ProductId)
{
if( User.Identity.IsAuthenticated ) {
//CartHelperClass.AddToCart(ProductId);
return PartialView();
} else {
return RedirectToAction("LogIn" , "Account" , new {
returnUrl = "Products" , subCat = Request.QueryString["subcat"]
});
}
}
//This is my PartialView code:
<span id="UpdateCart">(5)</span>
I would like to be able to take the data inside the partialVieew and update the span at the Top when I click the link.In my case I can not tell if AdToCart action result is even called.
What am I doing wrong herE?
You are using Products in the action link but your are using Product in Url link, maybe one of them is wrong.

Ajax.BeginForm says action doesn’t exists, however it does

I am working with AJAX Helper method in one my applications, things were all good and right but suddenly am facing this strange problem i.e. in view
<% using (Ajax.BeginForm("Feedback", "User", new AjaxOptions { InsertionMode = InsertionMode.InsertBefore, HttpMethod = "POST", OnFailure = "searchFailed", OnSuccess = "feedbackRecorded", LoadingElementId = "ajax-loader-fb", UpdateTargetId = "newsletter", }, new { #id = "feedback" })) { %>
The first parameter to Ajax.BeginForm that is the {action name} is now being marked in red color(I am using Resharper) and says that ‘cannot resolve action ‘ActionName’’, however the Action is present in my controller.
Another strange thing is that on running the app and submitting the form it ends up invoking the Javscript’s "OnSuccess” method as if it has succeeded but in actually nothing happened and it didn’t even get to first line call of the specified controllers action. (This is happening to both AJAX forms in the view)
Does anyone have any ideas about the possible reasons forit to behave this way suddenly?
Thankyou!
I just created a new 'SharedController' controller with the same action in it and now it is recognizing but its is not recognizing in the UserController?
public class SharedController : Controller
{
public ActionResult Feedback()
{
throw new NotImplementedException();
}
}
Maven, about ReSharper - it's complaining right, because you use this method overload
public static MvcForm BeginForm(
this AjaxHelper ajaxHelper,
string actionName,
Object routeValues,
AjaxOptions ajaxOptions,
Object htmlAttributes)
where second parameter is routeValues, so ReSharper looks for action 'Feeeback' in current controller.
Obviously, you wanted another overload, with this invocation
<% using (Ajax.BeginForm("Feedback", "User", null, new AjaxOptions { InsertionMode = InsertionMode.InsertBefore, HttpMethod = "POST", OnFailure = "searchFailed", OnSuccess = "feedbackRecorded", LoadingElementId = "ajax-loader-fb", UpdateTargetId = "newsletter", }, new { #id = "feedback" })) { %>
Pay attention to third null argument.
The second parameter of Ajax.BeginForm is the controller name.
Try changing the code to:
<% using (Ajax.BeginForm("Feedback", "Shared", ...

Categories

Resources