使用@ Ajax.ActionLink MVC将TextBoxFor值传递给控制器

时间:2017-05-31 07:33:40

标签: javascript jquery ajax asp.net-mvc

我在“同一”问题上经历了很多问题,但似乎没有一个问题适合我(或者我完全忽视了这一点)。

正如主题所说,我试图使用Ajax.ActionLink将值从TextBoxFor传递给我的控制器,但没有任何工作。我试过javascript / jquery并尝试使用我的模型,都返回null:

查看:

@Html.TextBoxFor(m => m.Duplicatename, new { @class = "form-control", @id = "txtDupName", @placeholder = "Enter duplicate name" })

@foreach (var item in Model.MasterBudgets)
    {
                   @{
                        var optsImportsl = new AjaxOptions()
                        {
                            HttpMethod = "GET",
                            InsertionMode = InsertionMode.ReplaceWith,
                            UpdateTargetId = "listofBudgets",
                            //OnBegin = "ImportLoading"
                        };
                    }

                    @if (User.IsInRole("Super Admin"))
                    {
                        @Ajax.ActionLink("Duplicate", "Duplicate", "Budget", new { id = item.BudgetId, type = item.Type, dupName = @Model.Duplicatename }, optsImportsl, new { @class = "btn btn-sm btn-black btn-outline", @id = "btnCreate" })
                    }
    }

控制器:

public ActionResult Duplicate(int id, string type, string dupName)
    {
        var model = _masterRepository.FindMasterBudgetById(id);

        if(dupName == null || dupName.Trim() == "")
        {
            dupName = "Duplicated";
        }



if (type == "Master")
            {
                var duplicate = Duplication(model, dupName);
                var masterbudgetId = _masterRepository.Save(duplicate);
                var budgets = _masterRepository.GetMasterBudgets
                                    .Where(x => x.ParentMasterBudgetId == id && x.Type == "Budget")
                                    .ToList();
                //Budgets
                foreach (var item in budgets)
                {
                    var linkedAccounts = _budgetAccountRepository.GetBudgetAccounts
                    .Where(x => x.BudgetId == item.BudgetId)
                    .ToList();
                    var duplicateBudgets = Duplication(item, dupName);
                    duplicateBudgets.ParentMasterBudgetId = masterbudgetId;
                    var getId = _masterRepository.Save(duplicateBudgets);
                    foreach (var account in linkedAccounts)
                    {
                        var budgetaccount = new BudgetAccount
                        {
                            BudgetId = getId,
                            BudgetAccountId = 0,
                            AccountId = account.AccountId,
                        };
                        var newaccountId = _budgetAccountRepository.Save(budgetaccount);
                    }

                    var linkedBudgetEntries = _budgetEntryRepository.GetBudgetLineEntries(item.BudgetId);

                    foreach(var lineEntryItem in linkedBudgetEntries)
                    {
                        var lineEntries = new Notes_Line_Entries
                        {
                            EntryLineId = lineEntryItem.EntryLineId,
                            fkiAccountId = lineEntryItem.fkiAccountId,
                            fkiNotesColumnId = lineEntryItem.fkiNotesColumnId,
                            Value = lineEntryItem.Value,
                            isNewEntry = lineEntryItem.isNewEntry,
                            budgetId = getId
                        };

                        _budgetEntryRepository.SaveDuplicateLineEntries(lineEntries,item.BudgetId);
                    }


                    var subbudgets = _masterRepository.GetMasterBudgets
                                    .Where(x => x.ParentBudgetId == item.BudgetId)
                                    .ToList();
                    //Sub-Budgets
                    foreach (var subItem in subbudgets)
                    {
                        var subBudgetLinkedAccounts = _budgetAccountRepository.GetBudgetAccounts
                        .Where(x => x.BudgetId == subItem.BudgetId)
                        .ToList();
                        var duplicateSubBudgets = Duplication(subItem, dupName);
                        duplicateSubBudgets.ParentMasterBudgetId = masterbudgetId;
                        duplicateSubBudgets.ParentBudgetId = getId;
                        duplicateSubBudgets.BudgetTypeName = subItem.BudgetTypeName;
                        duplicateSubBudgets.OrganisationId = subItem.OrganisationId;
                        var getSubBudgetId = _masterRepository.Save(duplicateSubBudgets);

                        foreach (var account in subBudgetLinkedAccounts)
                        {
                            var budgetaccount = new BudgetAccount
                            {
                                BudgetId = getSubBudgetId,
                                BudgetAccountId = 0,
                                AccountId = account.AccountId,
                            };
                            var newaccountId = _budgetAccountRepository.Save(budgetaccount);
                        }

                        var linkedSubBudgetEntries = _budgetEntryRepository.GetBudgetLineEntries(subItem.BudgetId);

                        foreach (var lineEntryItem in linkedSubBudgetEntries)
                        {
                            var lineEntries = new Notes_Line_Entries
                            {
                                EntryLineId = lineEntryItem.EntryLineId,
                                fkiAccountId = lineEntryItem.fkiAccountId,
                                fkiNotesColumnId = lineEntryItem.fkiNotesColumnId,
                                Value = lineEntryItem.Value,
                                isNewEntry = lineEntryItem.isNewEntry,
                                budgetId = getSubBudgetId
                            };

                            _budgetEntryRepository.SaveDuplicateLineEntries(lineEntries, subItem.BudgetId);
                        }

                    }
                }
                Success("Successfully duplicated " + model.BudgetName);
            }
return RedirectToAction("BudgetListInfo", new { searchTerm = String.Empty }); //This ActionResult being redirected to, returns a PartialView - This is done so that the items in the Table are returned in correct order(i.e. Parent, then children under the parent and children under the child items)
    }

复制功能:

private MasterBudget Duplication(MasterBudget model, string dupName)
        {
            return new MasterBudget
            {
                BudgetId = 0,
                BudgetName = model.BudgetName + " " + dupName,
                BudgetTracker = new Guid(),
                FinancialYear = model.FinancialYear,
                Description = model.Description,
                Status = model.Status,
                CreatedDate = DateTime.Now,
                CurrentWorkerId = CurrentUser.Id,
                OrganisationId = model.OrganisationId,
                BudgetTypeName = model.BudgetTypeName,
                ParentMasterBudgetId = model.ParentMasterBudgetId,
                Type = model.Type,
                CurrentWorkFlowTypeId = model.CurrentWorkFlowTypeId,
                ParentBudgetId = model.ParentBudgetId
            };
        }

我已经阅读了很多帖子,说客户端需要完成实际传递的值,因为使用模型,只能在提交时使用(服务器端) - 但我不知道如何: (我确定我只是愚蠢而且缺少一个基本的基础来让它发挥作用。

感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:0)

@Ajax.ActionLink()是Razor代码,在服务器上进行解析,以便new { ... dupName = @Model.Duplicatename }在发送模型之前将dupName的值设置为属性Duplicatename的原始值到浏览器。由于文本框,它不会神奇地改变。您需要使用javascript / jquery来响应客户端事件。

如果您使用$.ajax()方法而不是Ajax.ActionLink(),这将更容易。不清楚为什么要更改默认的id属性,我建议文本框只是

@Html.TextBoxFor(m => m.Duplicatename, new { @class = "form-control", @placeholder = "Enter duplicate name" })

然后在你的循环中,创建一个链接并将项属性添加为data属性

@foreach (var item in Model.MasterBudgets)
{
    if (User.IsInRole("Super Admin"))
    {
        <a href="#" class="duplicate btn btn-sm btn-black btn-outline" data-id="@item.BudgetId" data-type="@item.Type">Duplicate</a>
    }
}

请注意附加的类名(由于重复的id属性,您之前的实现也生成了无效的html)

然后添加以下脚本

var container = $('#listofBudgets');
var url = '@Url.Action("Duplicate", "Budget")';
var textbox = $('#Duplicatename');
// handle the click event of the links
$('.duplicate').click(function() {
    // get the values to be sent to the method
    var id = $(this).data('id');
    var type = $(this).data('type');
    var name = textbox.val();
    $.get(url, { id: id, type: type, dupName: name }, function(data) {
        container.html(data); // update the DOM
    });
});

作为旁注,您的方法应该是初始化模型并返回部分视图,而不是使用return RedirectToAction(....);