带列表的模型-从剃刀视图向列表中添加新项目的方法 [英] Model with List - approaches to add new item to the list from a Razor view

查看:81
本文介绍了带列表的模型-从剃刀视图向列表中添加新项目的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有各种属性的模型,但感兴趣的是另一种模型的列表.

I have a model with various properties but the one of interest is a List of another type of Model.

例如:

   public class User
    {
        public string Name { get; set; }
        public string Description { get; set; }

        public IEnumerable<UserInterest> Interests { get; set; }
    }

然后,我在视图中使用编辑器模板"为模型项目的每个项目渲染视图.

I then use an Editor Template within my view to render out a view for each item of the model items.

@Html.EditorFor(x => x.Interests)    

EditorFor模板类似于:

The EditorFor template looks something like:

@model Interest

<div>
    @Html.HiddenFor(x => x.Id)
    @Html.TextBoxFor(x => x.InterestText)
    @Html.CheckBoxFor(x => x.Delete)
   ....
</div>

与此处接受的答案非常相似的内容:包含以下项的模型列表型号(MVC-3,Razor)

Something very similar to the accepted answer here: Model Containing List of Models (MVC-3, Razor)

我的问题是-您如何从客户端(jQuery)在属性中创建新项目而不返回服务器.我目前有一个粗略的方法,可以将数据发布回我的控制器,该控制器将返回模型,并在Interests属性中添加一个新的空白项目.

My question is - how would you from the client-side (jQuery) create a new item within the property without going back to the server. I currently have a rough way of doing it whereby I post the data back to my controller which returns the model back with a new blank item within the Interests property.

这似乎在发出HTTP请求时显得过高,而且不太雅致.我当时在考虑使用jQuery .Clone(),但不能完全确定在命名元素和清除现有值方面需要做些什么.

This seems to be overkill making a HTTP request and not very elegent. I was thinking of using jQuery .Clone() but not entirely sure on what I'd need to do in terms of naming the elements and clearing existing values.

任何人都有任何建议.我希望能得到更多的意见和不同的方法.

So does anybody have any suggestions. I'm hoping to get more opinions and different approaches.

推荐答案

在这种情况下,我更喜欢使用客户端模板.您使用ajax将数据发送到服务器,然后接收JsonResult.查看 JsRender ,这是没有jQuery依赖的javascript库.

In such situations I prefer to use client templating. You send data to server with ajax and then receive JsonResult. Look at JsRender this is javascript lib without jQuery dependency.

这篇关于带列表的模型-从剃刀视图向列表中添加新项目的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆