I want to make a javascript that can dynamic insert a new "EditorFor" model, but i am having 2 problem.
1: i keep html encoding the string, and i can't figure out how to stop it.
2: How can i tell it what model to use instead of having a instance of it in my model
I have tryed the following but it dose not work :(
MvcHtmlString emodel = Html.EditorFor(model => new Cosplay.Models.Projects.CreatePartModel(), "CreatePartModel", "Parts[NAMEREPLACE]");
MvcHtmlString emodel = Html.EditorFor(model => Cosplay.Models.Projects.CreatePartModel, "CreatePartModel", "Parts[NAMEREPLACE]");
Here is my full javascript.
@model Cosplay.Models.Projects.CreatePartsModel
@{
ViewBag.Title = "AddParts";
}
<script type="text/javascript">
@{
MvcHtmlString emodel = Html.EditorFor(model => Cosplay.Models.Projects.CreatePartModel, "CreatePartModel", "Parts[NAMEREPLACE]");
string editor = emodel.ToString().Trim().Replace("\"", "\\\"");;
}
function getPartHtml(name) {
var html = '@editor';
return html.replace("NAMEREPLACE", name);
}
$(document).ready(function () {
var lastCount = 5;
$("#addPartInput").click(function () {
lastCount++;
$('#edit_part_list').append(getPartHtml(lastCount));
});
});
</script>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<div id="edit_part_list">
@Html.EditorFor(model => Model.Parts)
</div>
<a id="addPartInput">Add another part</a><br />
<input type="submit" value="Save" />
}
Edit: I have fixed problem 2 with the following, but problem 1 is still there.
Html.Editor("Parts[X]", "CreatePartModel").ToString().Replace("\"", "\\\"").Replace("\r\n", "\\n");
Edit 2: I have found that the following code will remove all input fields inside the edit model :(
Html.Editor("Parts[X]", "CreatePartModel")
Try like this:
This way you don't need any replacing. It will also take care of properly encoding.