What I need to do is to show a popup to add a new record to my database, im using bootstrap 3 and I love it because im not using a single line of jquery, and I have really n
Just for the record, I found my answer hope it helps someone else, it is really hard to find a full article of this.
I had to use more of jquery but It is a clean answer (I think).
Using data annotations in my model:
[Required]
public string Name { get; set; }
[Required]
public string Phone { get; set; }
Then I created a partial in my shared folder that contains my modal form, so I can make it global.
@model Controli.Models.Provider
And the script:
var frmnewprovider = $("#forms-providers-new");
$(document).ready(function () {
frmnewprovider.submit(function (e) {
e.preventDefault();
frmnewprovider.validate();
if (frmnewprovider.valid()) {
$.ajax({
url: "/Providers/Add",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
Name: frmnewprovider.find('#Name').val(),
Phone: frmnewprovider.find('#Phone').val(),
Email: frmnewprovider.find('#Email').val(),
Country: frmnewprovider.find('#Country').val(),
State: frmnewprovider.find('#State').val(),
Address: frmnewprovider.find('#Address').val()
}),
success: function (result) {
//if record was added to db, then...
window.location.replace('/Providers/Index'); //we can redirect
//or simply close our modal.
//$('#mdlnewprovider').modal('hide');
},
error: function(result) {
alert('error');
}
});
}
});
});
Now all I have to do to render my form where ever I need it is to add these lines:
@Html.Partial("Modals/Providers/FrmNew", new Provider())
@section scripts
{
}
Finally since my model was client-side validated I just add my model to my database, and redirect to Index view, while the ajax call hides active modal Update: I recommend to decide if redirect or hide modal at ajax call. like commented.
public ActionResult Add(Provider provider)
{
if (ModelState.IsValid) //Validate in server side too!
{
db.Providers.Add(provider);
db.SaveChanges();
return Json(new{ success = true}); //return a dummy json, you can pass what
//ever parameter you need. if code reach
//this point. it will always hit success
//in our ajax call
}
}
make sure your web.config contains:
Im using these scripts too:
Please let me know if something could be better.