如何从javascript填充模型中的列表字段?

时间:2017-09-08 13:15:16

标签: javascript jquery asp.net-mvc kendo-ui kendo-asp.net-mvc

我有一个Kendo.MVC项目。该视图的模型具有List<>类型的字段。我想从Javascript函数填充List。我已经尝试了几种方法,但无法使其发挥作用。有人可以解释我做错了吗?

所以这是我的模特:

public class Dashboard
{
    public List<Note> ListNotes { get; set; }
}

我在视图上使用ListNotes:

foreach (Note note in Model.ListNotes)
{
    @Html.Raw(note.NoteText)
}

如果我在视图开始时在控制器中填充Model.ListNotes,这是有效的。

public ActionResult DashBoard(string xsr, string vst)
    {
        var notes = rep.GetNotesByCompanyID(user.ResID, 7, 7);
        List<Koorsen.Models.Note> listNotes = new List<Koorsen.Models.Note>();

        Dashboard employee = new Dashboard
        {
            ResID = intUser,
            Type = intType,
            FirstName = user.FirstName,
            LastName = user.LastName,
            ListNotes = listNotes
        };

        return View(employee);
    }

...但我需要在用户操作后在Javascript中填充ListNotes。

这是我的javascript来进行ajax调用以填充ListNotes:

function getReminders(e)
{
    var userID = '@ViewBag.CurrUser';
    $.ajax({
        url: "/api/WoApi/GetReminders/" + userID,
        dataType: "json",
        type: "GET",
        success: function (notes)
        {
            // Need to assign notes to Model.ListNotes here
        }
    });
}

这是使用ajax调用调用的方法。我已经确认ListNotes确实有我想要的值;它不是空的。

public List<Koorsen.Models.Note> GetReminders(int id)
    {
        var notes = rep.GetNotesByCompanyID(id, 7, 7);
        List<Koorsen.Models.Note> listNotes = new List<Koorsen.Models.Note>();

        foreach (Koorsen.OpenAccess.Note note in notes)
        {
            Koorsen.Models.Note newNote = new Koorsen.Models.Note()
            {
                NoteID = note.NoteID,
                CompanyID = note.CompanyID,
                LocationID = note.LocationID,
                NoteText = note.NoteText,
                NoteType = note.NoteType,
                InternalNote = note.InternalNote,
                NoteDate = note.NoteDate,
                Active = note.Active,
                AddBy = note.AddBy,
                AddDate = note.AddDate,
                ModBy = note.ModBy,
                ModDate = note.ModDate
            };

            listNotes.Add(newNote);
        }

        return listNotes;
    }

如果ListNotes是一个字符串,我会添加一个隐藏字段并在Javascript中填充它。但这对ListNotes来说并不起作用。我没有收到错误,但屏幕上的文字没有变化。

@Html.HiddenFor(x => x.ListNotes)
...
...
$("#ListNotes").val(notes);

我也试过

@Model.ListNotes = notes; // This threw an unterminated template literal error

document.getElementById('ListNotes').value = notes;

我甚至在分配值后尝试刷新页面:

window.location.reload();

并刷新代码所在的面板栏

var panelBar = $("#IntroPanelBar").data("kendoPanelBar");
panelBar.reload();

有人可以解释如何让它发挥作用吗?

我不知道这是否会影响这个问题,但我需要在javascript中使用ajax调用填充模型的原因是因为Model.ListNotes正在Kendo Panel Bar控件中使用而且我没有&# 39; t希望Model.ListNotes具有一个值,直到用户扩展面板栏。

这是面板栏的代码:

@{
    @(Html.Kendo().PanelBar().Name("IntroPanelBar")
        .Items(items =>
        {
        items
        .Add()
        .Text("View Important Notes and Messages")
        .Expanded(false)
        .Content(
            @<text>
                    @RenderReminders()
            </text>
                );
        }
        )
    .Events(e => e
    .Expand("getReminders")
    )
    )
}

这里是帮助者,而不是呈现内容:

@helper RenderReminders()
{
    if (Model.ListNotes.Count <= 0)
    {
         @Html.Raw("No Current Messages");
    }
    else
    {
         foreach (Note note in Model.ListNotes)
         {
               @Html.Raw(note.NoteText)
               <br />
         }
    }
}

如果我在控制器中填充Model.ListNotes并将Model传递给视图,则面板栏和帮助程序可以正常工作。在用户展开面板栏后,我无法在javascript中填充它。

1 个答案:

答案 0 :(得分:0)

也许这将为您做到。我将提供一个小的工作示例,我相信您可以轻松扩展以满足您的需求。我建议手动编写html,而不要使用诸如@ html.raw之类的辅助方法,因为@ html.raw只是最终生成html的工具。您可以手动编写html来完成辅助方法的操作,我认为在这种情况下会更轻松。如果您正确地编写了html,则它应该正确地绑定到模型(这意味着在您的后期请求模型中不会为空),因此,如果您使用javascript正确地修改了该html,那么它也将正确地绑定到模型。 >

看看其中一些例子,以更好地了解我在说什么:

http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx

http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/

所以回答您的问题... 您可以构建一个隐藏的容器来保存这样的列表值(确保此容器位于表单内):

<div id="ListValues" style="display:none">
</div>

然后将ajax发布的结果放入javascript变量(未显示)。 然后在javascript中执行以下操作:

        $('form').off('submit'); //i do this to prevent duplicate bindings depending on how this page may be rendered futuristically as a safety precaution.
        $('form').on('submit', function (e) { //on submit, modify the form data to include the information you want inside of your ListNotes
            
            var data = getAjaxResults(); //data represents your ajax results. You can acquire and format that how you'd like I will use the following as an example format for how you could save the results as JSON data: [{NoteID ="1",CompanyID ="2"}] 
            
            let listLength = data.length;
            for (let i = 0; i < listLength; i++) {
                $('#ListValues').append('<input type="text" name="ListNotes['+i+'].NoteID " value="' + data.NoteID +'" />') 
                $('#ListValues').append('<input type="text" name="ListNotes['+i+'].CompanyID " value="' + data.CompanyID +'" />') 
                 //for your ajax results, do this for each field on the note object
            }
            
        })

应该这样做!提交表单后,它将自动将模型绑定到您的ListNotes!您将可以在后控制器操作中在调试器中检查此错误。