开发者

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...

$("#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.

my task_fields partial is something like this

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

I just want the add_task link to work properly.

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".


Have a look at jquery the jquery template plugin. It's a different but IMO much cleaner approach for this scenario.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜