简体   繁体   English

如何使用jQuery追加局部变量? 剃刀-ASP.NET MVC-jQuery

[英]How to append partials using jquery? Razor - asp.net mvc - Jquery

Say I want to create a form that allows you to add elements dynamically through javascript... for example, a project with many tasks... 假设我想创建一个表单,该表单允许您通过javascript动态添加元素...例如,一个有很多任务的项目...

$("#add_task").click(function () {
            $('#tasks').append('@Html.Raw(Html.Partial("_task_fields").ToHtmlString())');
        });

I seem to be having problems with this approach cause the javascript isnt encoded... and using HttpUtility.JavaScriptStringEncode adds extra quotation marks to the elements that have attributes like class"someClass" for instance. 我似乎在这种方法上遇到问题,导致未对javascript进行编码...,并使用HttpUtility.JavaScriptStringEncode向具有类“ someClass”等属性的元素添加了额外的引号。

my task_fields partial is something like this 我的task_fields部分是这样的

<tr>
     <td>
         Task
     </td>
     <td>
        <input type="text" name="task[name]" />
     </td>
</tr>

I just want the add_task link to work properly. 我只希望add_task链接正常工作。

Please help. 请帮忙。

Ok. 好。 You will do it but little different way. 您将执行此操作,但几乎没有其他方法。 Write action to controller instead of partial. 将动作写入控制器,而不是部分动作。

public class HomeController : Controller
{
        public ActionResult MyPartial(/*some parameters*/)
        {
            object someData = foo(/*some parameters*/);
            return PartialView("_MyPartial", someData);
        }
}

**And call action with Ajax.**

$("#add_task").click(function () {
$('#taskItem').load(@Url.Content("~/home/MyPartial"));
....
})

Of course you can add to "task" after loaded "taskItem". 当然,您可以在加载“ taskItem”后添加到“ task”。

Have a look at jquery the jquery template plugin. 看看jquery的jquery模板插件。 It's a different but IMO much cleaner approach for this scenario. 在这种情况下,这是另一种方法,但IMO更加清洁。

Apart from using a jquery template only approach, you could also render the partial into a jquery template block and combine both technologies this way if you want. 除了使用仅使用jquery模板的方法之外,您还可以将部分渲染到jquery模板块中,并根据需要以这种方式组合这两种技术。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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