ASP.NET MVC 4 Passing Object Variable Through ActionLink

南笙酒味 提交于 2019-11-26 17:18:41

问题


I have an ASP.NET MVC 4 application. There is a razor view in my application that works with List type as a model.

@model List<MeetingLog.Models.UserModel>

@{
    Layout = null;
}
.
.
.

I am iterating through Model variable like this:

@foreach (var item in Model)
                {
                    <tr>
                        <td>
                            @item.Name
                        </td>
                        <td>
                            @item.Surname
                        </td>
                        <td>
                            @Html.ActionLink("Click", "SavePerson", "Meeting", new {model = item, type = "coordinator"}, null)
                            @Html.ActionLink("Click", "SavePerson", "Meeting", new {model = item, type = "participant"}, null)
                        </td>
                    </tr>
                }

I need to pass two variables to SavePerson action with action links. First one is current UserModel, and second one is string variable named type. But in my action first parameter comes through as null. But string parameter comes correctly. How can I achieve this?


回答1:


I use ajax calls for this

$('.btnSave').on('click', function(){
    $.ajax({
        url: '@(Url.Action("SavePerson", "Meeting"))',
        type: 'post',
        data: {
            Value1: 'Value1',
            Value2: 'Value2'
        },
        success: function (result) {
            alert('Save Successful');
        }
    });
});

and put the call in a button click or a link click if you want with href = # hopefully this helps.




回答2:


You can not pass instances complex types through querystring. This is the way to use it:

@Html.ActionLink("Click", "SavePerson", "Meeting", new {x = item.x, y = item.y, ..., type = "participant"}, null)



回答3:


You actually can, it's just a little weird, when you are coding the passed values (new{}) what you have to do is pass it as a new object that you are constructing so it ends up being:

@Html.ActionLink("Link Name", "LinkActionTarget", new Object{model = item, type ='Coordinator'}

Where Object is the name of your object, and model and type are attributes of that object



来源:https://stackoverflow.com/questions/19359204/asp-net-mvc-4-passing-object-variable-through-actionlink

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!