简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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