I really dislike page loads, I think they detract from the user experience, so I'm trying to make my web application heavily AJAX-ified.
When the user clicks on "Add new", Javascript generates a form based on a model using Razor, with the following code:
<script type="text/javascript">
var strNewCategoryForm = '<div><i class="glyphicon glyphicon-folder-open rightfolderpadding"></i>@using (Html.BeginForm("AddCategory", "Password", FormMethod.Post, new { @class="newcategoryform", role = "form", id="[1]" })) { @Html.AntiForgeryToken() @Html.PasswordFor(m => m.Category_ParentID, new { type = "hidden", value = "0" }) @Html.PasswordFor(m => m.CategoryName, new { type = "text" }) <span class="btn-group groupalign"><a href="#" onclick="saveNewCategory(\'#[2]\');return false;" class="btn btn-xs btn-primary"><i class="glyphicon glyphicon-save"></i>Save</a></span> }</div>';
</script>
The code works great, Razor is able to generate the form within the string, so I dont have any issues with making this work. However, for code readability and ease of development, it's not that great.
I'm still quite new to MVC and razor, so I'm just wondering, is there a better or "MVC/Razor standard" way of doing this, that I don't know about?
Edit: In case anyone is interested, I've used both bits of Exception's answers:
In the partial view:
@model Secure_Password_Repository.Models.Category
<div><i class="glyphicon glyphicon-folder-open rightfolderpadding"></i> \
@using (Ajax.BeginForm("AddCategory", "Password", new AjaxOptions { HttpMethod="post", OnFailure="" }, new { @class="newcategoryform", role = "form", id="[1]" }))
{
@: \
@Html.AntiForgeryToken() @: \
@Html.HiddenFor(m => m.Category_ParentID, new { value = "0" }) @: \
@Html.TextBoxFor(m => m.CategoryName) @: \
@: <span class="btn-group groupalign"><a href="#" onclick="saveNewCategory(\'#[2]\');return false;" class="btn btn-xs btn-primary"><i class="glyphicon glyphicon-save"></i>Save</a></span> \
}</div>
In the main view:
<script type="text/javascript">
var strNewCategoryForm = '@Html.Partial("_NewCategoryForm")';
</script>
The "\" at the end of each line in the partial view tell JavaScript that each line is continuation of a string value.