简体   繁体   中英

Passing parameter from View to Controller MVC using Ajax helper

Iam trying to pass parameters from the view to controller using the Ajax helper but i dont know what i am missing, i cant get it working!!!

here is the code:

In the controller:

 [HttpGet]
    public ActionResult InsertEvent(int? id)
    {

        return View();
    }

The View:

foreach (var item in Model)
{
    <hr />
    @Ajax.ActionLink(item.First_Name +" "+ item.Last_Name, null, null, new { id = item.Id },
        new AjaxOptions {
        HttpMethod = "GET",
        OnBegin = "FillName('"+ item.First_Name+ "', '"+item.Last_Name+"')"

    }, new { @class = "clickOnCostumer", @href="#"});
}

can anyone help please? i look over many tutorials and they are showing the same solution.. am i missing something?

here is a pic of the debugg it seems all is good but its not returning the value to the controller:

在此处输入图片说明

Two things;

Avoid sending multiple calls to the controller inside a loop. That's a major performance issue. Use Jquery get method. It's simple and easy to use. Here is an example.

@model Models.MyList2
@{
    ViewBag.Title = "Home Page";
    string allIndexes = "";

    if (Model.Any())
    {
        allIndexes = string.Join(",", Model);
    }
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>   

<script type="text/javascript">
    jQuery(document).ready(function($) {
        $.get("\MyController\MyMethod", { variablename: '@allIndexes' }, function(result) {
            $("#anotherinput").val(result);
        });
    });
</script>

尝试设置AjaxOptions对象的URL值,或者考虑是否正确使用了ActionLink方法的参数。

@Ajax.ActionLink(linkText: item.First_Name +" "+ item.Last_Name, 
             actionName: "InsertEvent", 
             routeValues: new { id = item.Id }, 
             ajaxOptions: new AjaxOptions
             {
                 HttpMethod = "GET",
                 OnBegin = "FillName('"+ item.First_Name+ "', '"+item.Last_Name+"')"
             }, 
             htmlAttributes: new { @class = "clickOnCostumer", @href="#"})

It might help to explicitly detail which part is for each parameter. Also you might need to add the InsertionMode under the ajaxOptions. For example in what I needed in my code, I had to do a replace, so I had to add in, where the updateTargetId is the div enclosing my html:

                 InsertionMode = InsertionMode.Replace,
                 UpdateTargetId = "rightPanelContent"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM