I have the following scripts that existed in the project, its already bundled and rendered in the layout page:
Code in BundleConfig.cs
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
<div class="container body-content">
@RenderBody()
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
The index page uses the _layout, when pressing the add button, i am rendering partial view inside a div in the index page:
function LaodDivToSave() {
$(document).ready(function () {
var div = $("#DivAppendPartialView");
div.load('@Url.Action("Create", "Product")');
})
}
The Partial View "Create":
@model Lib.Models.Product
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.EditorForModel()
<div class="col-md-offset-2 col-md-10">
<input type="button" value="Save" class="btn btn-default" onclick="CreateProduct()" />
</div>
</div>
</div>
}
The editor template
@model lib.Models.Product
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Price)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Price)
@Html.ValidationMessageFor(model => model.Price)
</div
and finally the model class:
public class Product
{
public int ProductId { get; set; }
[Required(ErrorMessage = "Please provide name!")]
[StringLength(100, ErrorMessage = "name is too long!")]
[Display(Name = "Name")]
public string Name { get; set; }
[Required(ErrorMessage = "Please provide price!")]
[Range(1, 100, ErrorMessage = "Product price must be between 1 and 100!")]
public decimal Price { get; set; }
}