Ihor Mykytiv
Ihor Mykytiv

Reputation: 99

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"].

Upvotes: 0

Views: 414

Answers (1)

Andrei
Andrei

Reputation: 56688

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;

Upvotes: 1

Related Questions