I'm developping a web application for searching media, so for my interface of search i should have somthing like that : the user specify the 4 fields and he can add an other fields(the same fields nature but he want to add an other criterion) by clicking on the icon Plus, i have done that with jquery, see the image below:enter image description here
But my problem is that: How can i pass the liste of form values to my action!!
here you are the code of my controller and my view (i do it just for one )
Controller:
[HttpPost]
public ActionResult RechercheForm(Recherche FormData)
{
List<Asset> liste = null;
if (FormData.Op == "Like")
{
if (FormData.Critere == "Titre")
{
liste = bdd.Assets.Where(a => (a.Titre.Contains(FormData.Val1)
)).ToList();
ViewBag.Val = FormData.Val1;
return View("Index",liste);
}
else
if (FormData.Critere == "TitreCourt")
{
liste = bdd.Assets.Where(a => (a.TitreCourt.Contains(FormData.Val1)
)).ToList();
return View("Index", liste);
}
}
return View("Index");
}
View:
<div class="right-content" style="width: 760px;" >
<!-- DropListDownData -->
#{
Dictionary<string, string> ListCritere=new Dictionary<string, string>
{
{"Titre", "Titre"},
{"TitreCourt", "TitreCourt"},
// some lines skipped
};
Dictionary<string, string> ListOp = new Dictionary<string, string>
{
{"Like", "Like"},
{"Sup", "Sup"},
{"Inf", "Inf"},
// some lines skipped
};
}
#using (Html.BeginForm("RechercheForm", "Recherche",new { ReturnUrl = ViewBag.ReturnUrl },FormMethod.Post, new { #class = "form-inline" })){
<button type="submit" class="btn btn-default">Rechecrcher</button>
<table id="TableRech">
<tr>
<th>Critere</th>
<th>Opérateur</th>
<th>Valeur1</th>
<th>Valeur2</th>
<th></th>
</tr>
<tr>
<td><div class="form-group">
#Html.DropDownList("Critere", new SelectList(ListCritere, "Key", "Value"),new { #class = "form-control" })
</div></td>
<td><div class="form-group">
#Html.DropDownList("Op", new SelectList(ListOp, "Key", "Value"),new { #class = "form-control" })
</div></td>
<td><div class="form-group">
#Html.TextBox("Val1",null,new {id = "Val2", #class = "textbox", style="width:50px;padding-right: 50px; " })
</div></td>
<td> <div class="form-group">
#Html.TextBox("Val2",null,new {id = "Val2", #class = "textbox", style="width:50px;padding-right: 50px; " })
</div></td>
<td><span class="glyphicon glyphicon-plus-sign" id="Plus" style="width: 15px;" onclick="RechFunctionPlus()" ></span></td>
</tr>
</table>
}
</div>
</div>
<script>
function RechFunctionPlus() {
var table= document.getElementById('TableRech');
var tr = document.createElement('tr');
table.appendChild(tr);
var td = document.createElement('td');
td.innerHTML='<select class="form-control" id="Critere" name="State"> <!-- some attrs=ibutes skipped --><option value=""></option><option value="Titre">Titre</option><option value="TitreCourt">TitreCourt</option><option value="Type">Type</option></select>';
tr.appendChild(td);
var td2 = document.createElement('td');
td2.innerHTML='<select class="form-control" id="Op" name="State"> <!-- some attrs=ibutes skipped --><option value=""></option><option value="Like">Like</option><option value="Inf">Inf</option><option value="Sup">Sup</option></select>';
tr.appendChild(td2);
var td3 = document.createElement('td');
td3.innerHTML='#Html.TextBox("Val1",null,new {id = "Val1", #class = "textbox", style="width:50px;padding-right: 50px; " })';
tr.appendChild(td3);
var td4 = document.createElement('td');
td4.innerHTML='#Html.TextBox("Val2",null,new {id = "Val2", #class = "textbox", style="width:50px;padding-right: 50px; " })';
tr.appendChild(td4);
var td5 = document.createElement('td');
td5.innerHTML='<span class="glyphicon glyphicon-minus-sign" id="Plus" style="width: 15px;" onclick="RechFunctionMoins()" ></span>';
tr.appendChild(td5);
}
</script>
i think to do a list of the calss "Recherche" that i will pass it to my Action "RechercheForm" but i don't how?!!
Use JavaScript
For example:
function sendForm(projectId, target) {
$.ajax({
url: target,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
projectId: projectId,
userAccountIds: [1, 2, 3]
}),
success: ajaxOnSuccess,
error: function (jqXHR, exception) {
alert('Error message.');
}
});
}
See this post Post JavaScript array with AJAX to asp.net MVC controller
Related
In my ASP.NET MVC project, there is a table that shows the user view the information of file type and Id (Hidden).
Whenever the user put checked the checkboxes and clicks on the Send Request Mail Button, I want to get the IDs of the checked rows and pass them to the controller as a List of Ids.
This is the table view
<tbody>
#foreach (var item in Model.ReqDocumentsViewModel.OrderByDescending(x => x.Id))
{ <tr class="even pointer">
<td style="display:none;">#item.Id</td>
<td>#item.FileType</td>
<td>#item.Note</td> #if (item.RequestStatus == false) { <td> Not Requested; </td> } else { <td> Requested; </td> } <td>
<input type="checkbox" value="#item.Id" id="chk" />
</td>
<td>
<button type="button" onclick="RemoveReqDocument()" class="btn btn-danger">Remove</button>
</td>
</tr>
}
</tbody>
<button type="button" class="btn btn-primary sm" onclick="SendMailNotification();">Send Request Mail</button>
This is what I tried.
function SendMailNotification() {
const selectedRows = [...$('table tbody tr:has("input:checked")')]
.map(tr => [...$(tr).find('td:lt(1)')]
.reduce((res, td) => (res[$(td).attr('prop')] = $(td).text(), res), {}))
console.log(selectedRows)
var newOrders = $.map(selectedRows, function (element) {
var obj = {};
for (var key in element) {
obj.Id = key;
}
return obj;
});
$.ajax({
type: "POST",
url: "/Task/RequestDocument",
data: JSON.stringify(newOrders),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
if (r == false) {
alert("You have to enter Order Qty first");
} else {
alert("Order Created");
location.reload();
}
}
});
}
In Controller
public JsonResult RequestDocument(List < ReqDocList > idQs)
{
}
Model
public class ReqDocList
{
public int Id { get; set; }
}
I want to get the IDs of the checked rows and pass them to the
controller as a List of Ids.
Below is a work demo, you can refer to it.
ReqDocListVM:
public class ReqDocListVM
{
public ICollection<ReqDocList> ReqDocList { get; set; }
}
TaskController:
public class TaskController : Controller
{
public static List<ReqDocList> ReqDocList = new List<ReqDocList>()
{
new ReqDocList() {Id =1},
new ReqDocList() {Id =2},
new ReqDocList() {Id =3},
new ReqDocList() {Id =4}
};
public IActionResult Index()
{
var model =new ReqDocListVM();
model.ReqDocList= ReqDocList;
return View(model);
}
public JsonResult RequestDocument(List<int> ids)
{
return Json(ids);
}
}
Index view:
#model ReqDocListVM
<table class="table table-bordered table-light">
<tbody>
#foreach (var item in Model.ReqDocList)
{
<tr class="even-pointer" chk-id="#item.Id">
<td>
<input type="checkbox" value="#item.Id" id="chk" />
</td>
<td>
<button type="button" onclick="RemoveReqDocument()" class="btn btn-danger">Remove</button>
</td>
</tr>
}
</tbody>
</table>
<button id="bt"type="button" class="btn btn-primary sm" >Send Request Mail</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var Ids = [];
$(".even-pointer").click(function () {
$(this).toggleClass("selected");
var Id = $(this).attr('chk-id');
if ($(this).hasClass("selected")) {
Ids.push(Id);
}
else {
Ids = Ids.filter(function (id) {
return id !== Id;
});
}
});
$("#bt").click(function () {
console.log(Ids);
$.ajax({
type: "POST",
url: "/Task/RequestDocument",
data: { "ids": Ids },
success: function (response) {
alert(response);
}
});
});
});
</script>
result:
I have an MVC website using Razor views. My Model is a List<Device>. In this particular view I need to enter a serial number for the device's box and, if it matches the device's serial number, change the dropdown enum from LabelPack to SystemPack. Finally, the controller will update the device's status in the DB.
Here is the relevant code from the view:
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.SerialNumber)
</td>
<td>
<input type="text" id=#item.SerialNumber name=#item.SerialNumber oninput="return boxSerialNumberInput(#item.SerialNumber)" />
</td>
<td>
<div class="col-md-10" id="#item.SerialNumber">
#Html.EnumDropDownListFor(modelItem => item.Status, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(modelItem => item.Status, "", new { #class = "text-danger" })
</div>
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
#Html.ActionLink("Details", "Details", new { id = item.ID })
</td>
</tr>
}
My question is basically: How do I check if the input serial number matches the device's serial number and update the dropdown? I assume there is a way to do this with JavaScript so I am calling a JavaScript method with the onInput event. However, I don't know what to put in the JavaScript method.
Fortunately, a coworker was able to help me with this. I'm sorry I didn't give enough information in the initial question. I really thought there would be an easy way to do this but it seems there is now. Below is the complete code from my view in case someone else stumbles into the same problem.
#model IEnumerable<DHLScanner.Models.Device>
#{
ViewBag.Title = "LabelPackStationView";
}
#using (Html.BeginForm("LabelPackStation", "Device", FormMethod.Post, new { id = "frmPackStation" }))
{
<p>
Find by serial number: #Html.TextBox("SearchString")
<input type="submit" value="Search" />
</p>
<div>
<h4>Device</h4>
<hr />
<dl class="dl-horizontal"></dl>
</div>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.SerialNumber)
</th>
<th>
#Html.DisplayName("Box Serial Number")
</th>
<th>
#Html.DisplayNameFor(model => model.Status)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
<span id="sp_#item.ID">#Html.DisplayFor(modelItem => item.SerialNumber)</span>
</td>
<td>
<input type="hidden" id="hdn_#item.ID" value="#item.ID" />
<input type="text" id="ser_#item.ID" oninput="return boxSerialNumberInput(#item.SerialNumber)" />
</td>
<td>
<div class="col-md-10">
#Html.EnumDropDownListFor(modelItem => item.Status, htmlAttributes: new { #class = "form-control", id = "ddl_" + #item.ID, name = "ID" })
#Html.ValidationMessageFor(modelItem => item.Status, "", new { #class = "text-danger" })
</div>
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
#Html.ActionLink("Details", "Details", new { id = item.ID })
</td>
</tr>
}
</table>
<p id="test"> xyz</p>
<p id="links">
#Html.ActionLink("Back to Prep", "PrepStation", "Order", new { id = ViewBag.Order.ID }, null)
#{
if (ViewBag.ShowSystemPackView)
{
#Html.ActionLink("Advance to System Pack", "SystemPackStation", "Order", new { id = ViewBag.Order.ID }, null)
}
}
</p>
<input type="hidden" name="testField" value="a value here" id="testField" />
<input type="hidden" id="hdn_Url" value="#ViewBag.Url" />
<input type="hidden" id="hdn_OrderId" name="ID" value="#ViewBag.Order.ID" />
<button id="btn_Refresh" name="pageRefrersh" value="refresh">Refresh</button>
}
#*<form action="" method="post"></form>*#
<script type="text/javascript">
function RegisterEvents(){
$('input[id^="ser"]').blur(function () {
var Id = $(this).siblings('input[type="hidden"]').val();
var lbl = $('span[id="sp_' + Id + '"]');
if ($(this).val() == lbl.html()) {
$('select#ddl_' + Id).val('3');
}
});
$('button[id="btn_Refresh"]').click(function () {
CollectDeviceData();
return false;
});
}
function CollectDeviceData() {
var devices = new Array();
// Collect Data
$.each($('input[id^="ser"]'), function () {
var Id = $(this).siblings('input[type="hidden"]').val();
var orderId = $('input[id="hdn_OrderId"]').val();
var device = {};
device.Id = Id;
device.Status = $('select#ddl_' + Id).val();
device.OrderID = orderId;
devices.push(device);
});
var jsonObject = {
devices: JSON.stringify(devices)
};
//Return Data
var results = function (data) {
window.location.href = $('input[id="hdn_Url"]').val();
};
PostBack(jsonObject, results);
}
function PostBack(jsonObject, result) {
var url = $('input[id="hdn_Url"]').val();
$.ajax({
url: url,
type: 'post',
data: jsonObject,
success: result,
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}
});
}
$(document).ready(function () {
RegisterEvents();
});
</script>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
I want to send multiple records in the database using javascript in asp.net mvc i tried many different ways but all in vain. here I have the best code which can send the data to the controller but the file is not sending.
I search different ways i have found one is with FormData but i am unable to handle that in this context.
Controller:
public ActionResult SaveAllFeedback(FEEDBACKVM[] fEEDBACKs)
{
try
{
if (fEEDBACKs != null)
{
FEEDBACK fEEDBACK = new FEEDBACK();
foreach (var item in fEEDBACKs)
{
fEEDBACK.DATE = item.DATE;
fEEDBACK.COMMENT = item.COMMENT;
fEEDBACK.STUDENTID = item.STUDENTID;
fEEDBACK.TEACHERID = db.TEACHERs.Where(x => x.EMAIL == User.Identity.Name).FirstOrDefault().ID;
if (item.HOMEWORK != null)
{
fEEDBACK.HOMEWORK = SaveToPhysicalLocation(item.HOMEWORK);
}
db.FEEDBACKs.Add(fEEDBACK);
}
db.SaveChanges();
return Json("Done", JsonRequestBehavior.AllowGet);
}
return Json("Unable to save your feedback! Please Provice correct information", JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
return Json("Unable to save your feedback! Please try again later.", JsonRequestBehavior.AllowGet);
}
}
ViewPage:
<form>
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<input name="DATE" id="DATE" type="date" class="form-control" />
</div>
<table class="table table-responsive table-hover" id="table1">
<thead>
<tr class="bg-cyan">
<th></th>
<th>RollNumber</th>
<th>Comment</th>
<th>Homework</th>
</tr>
</thead>
<tbody>
#foreach (var item in ViewBag.students)
{
<tr>
<td>
<input name="STUDENTID" type="text" value="#item.Key" hidden="hidden" />
</td>
<td>
<input name="STUDENTROLLNUMBER" type="text" value="#item.Value" class="form-control" readonly="readonly" />
</td>
<td>
<input name="COMMENT" type="text" class="form-control" />
</td>
<td>
<input name="HOMEWORK" type="file" class="form-control" />
</td>
</tr>
}
</tbody>
</table>
<div class="form-group">
<div class="col-md-10">
#Html.ValidationMessage("ErrorInfo", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button id="saveButton" type="submit" class="btn btn-danger">Save Attendance</button>
</div>
</div>
</form>
Script:
<script>
//After Click Save Button Pass All Data View To Controller For Save Database
function saveButton(data) {
return $.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '#Url.Action("SaveAllFeedback", "Teacherss")',
data: data,
success: function (result) {
alert(result);
location.reload();
},
error: function () {
alert("Error!")
}
});
}
//Collect Multiple Order List For Pass To Controller
$("#saveButton").click(function (e) {
e.preventDefault();
var formData = new FormData();
var arr = [];
arr.length = 0;
$.each($("#table1 tbody tr"), function () {
//arr.push({
// //DATE: $("#DATE").val(),
// //STUDENTID: $(this).find('td:eq(0) input').val(),
// //COMMENT: $(this).find('td:eq(2) input').val(),
// //HOMEWORK: $(this).find('td:eq(3) input').val()
// });
formData.append("DATE", $("#DATE").val());
formData.append("STUDENTID", $(this).find('td:eq(0) input').val());
formData.append("COMMENT", $(this).find('td:eq(2) input').val());
formData.append("HOMEWORK", $(this).find('td:eq(3) input')[0].files[0]);
});
var data = JSON.stringify({
fEEDBACKs: formData
});
$.when(saveButton (data)).then(function (response) {
console.log(response);
}).fail(function (err) {
console.log(err);
});
});
</script>
I just want to send multiple records with the file to the database
are you sure you want send the files???? if yes then
Your form tag should be look like this
<form id="yourid" action="youraction" enctype="multipart/form-data">
Form Component
</form>
NOTE:- enctype="multipart/form-data" tag is important
and then controller should be look like this
public ActionResult YourController(FormCollection data)
{
if (Request.Files.Count > 0)
{
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
//you can save the file like this
string path = Server.MapPath("~/Yourpath/FileName" + fileName.Substring(fileName.LastIndexOf('.')));
file.SaveAs(path);
//or you can load it to memory like this
MemoryStream ms = new MemoryStream();
file.InputStream.CopyTo(ms);
//use it how you like
}
}
return View();
}
I have Order table and OrderNotes table. OrderNotes have foreign key OrderID in it. I want to use AJAX to insert JSON data into my OrderNotes table. Below is my code
Here is asps file that contains Ajax which
<script>
$(document).ready(function () {
$.ajax({
url: "Orders/Index",
type: 'POST',
success: function (data) {
$("#divContent").html(data);
$('.dropdown').hover(function () {
var $text = $(this).closest("tr").find(".nearest").text();
$.ajax({
url: "OrderNotes/Index?orderId=" + $text + "",
type: 'POST',
success: function (data) {
$(".orderContent").html(data);
function CreateOrderNotes() {
var Bywho = $("#By").val();
var NoteBy = $("#Note").val();
var OrderIdgiven = $("#OrderID").val();
var $text = $(this).closest("tr").find(".nearest").text();
$.ajax({
type: "POST",
URL: "OrderNotes/Create",
data: JSON.stringify({
By: Bywho, Note: NoteBy, OrderID: OrderIdgiven
}),
contentType: "application/json",
success: function (result) {
$("#table").append("<tr><td>" +
result.OrderNotesID + "</td><td>" +
result.By + "</td><td>" +
result.Note + "</td><td>" +
result.OrderID + "</td></tr>")
}
});
}
}
});
});
}
});
});
</script>
<div id="divContent" class="container">
</div>
Order Controller and view is not important so have excluded those files.
OrderNotes View and controller
OrderNotes Controller
namespace Ordernotes.Controllers
{
public class OrderNotesController : Controller
{
private OrderDbContext db = new OrderDbContext();
// GET: OrderNotes
public ActionResult Index(int orderid)
{
List<OrderNote> OrderNotesforOrderId = new List<OrderNote>();
if (db.Orders != null)
{
List<OrderNote> notesforeachorder = db.OrderNotes.Where(m => m.OrderID == orderid).ToList();
foreach (var ev in notesforeachorder)
{
OrderNotesforOrderId.Add(ev);
}
}
return PartialView(OrderNotesforOrderId);
}
[HttpPost]
public ActionResult Create(OrderNote orderNote)
{
OrderDbContext entities = new OrderDbContext();
var notes = new OrderNote();
notes.By =orderNote.By;
notes.Note = orderNote.Note;
notes.OrderID = orderNote.OrderID;
entities.OrderNotes.Add(notes);
entities.SaveChanges();
return Json(notes, JsonRequestBehavior.AllowGet);
}
}
}
OrderNotes Index
#model IEnumerable<Ordernotes.Models.OrderNote>
<table class="table" id="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.OrderNoteID)
</th>
<th>
#Html.DisplayNameFor(model => model.Note)
</th>
<th>
#Html.DisplayNameFor(model => model.By)
</th>
<th>
#Html.DisplayNameFor(model => model.OrderID)
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.OrderNoteID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Note)
</td>
<td>
#Html.DisplayFor(modelItem => item.By)
</td>
<td>
#Html.DisplayFor(modelItem => item.OrderID)
</td>
</tr>
}
</table>
<div class="notesfooter div-table">
#Html.Partial("Create",new Ordernotes.Models.OrderNote())
</div>
OrderNotes Create
#model Ordernotes.Models.OrderNote
<div class="form-horizontal">
<div class="form-group">
#Html.LabelFor(model => model.By, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.By, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Note, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.Note, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.OrderID, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<a id="savesnotes" onclick="CreateOrderNotes()" class="btn btn-default" >Save</a>
</div>
</div>
</div>
Only Ajax third call is not working. Can't figure out how to send JSON data and what parameter to pass in Create in OrderNotes Create function.
I'm working in MVC and i have one scenario as follows:
I have a view called ManageResource where i il show the available resource's in grid and a button to add new resource. if i click on the add new resource button a popup il open with the partialview inside it, i have to display the validation result in popup itself when i click save with out entering any values and when i enter the required fields the values should be populated in the grid and the popup should be closed.`
"iam not getting validation result in popup, but can able to save data's"
following is my code:
Model-tblUser
public partial class tblUser
{
public int UID { get; set; }
[Required]
public int EmpID { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public decimal Salary { get; set; }
}
View-ManageResource
function Create() {
BootstrapDialog.show({
title: "Add Resource",
message: $('<div id="CreatePopup"></div>').load('#Url.Action("Create", "Resource")')
});
return false;
}
<input type="button" id="AddNewCompany" onclick="Create()" class="push_button blue btn_width" value="Add New Resource" />
partial view- Create
function SaveResource() {
var obj = [];
var EmpID = $('#EmpID').val();
var FirstName = $('#FirstName').val();
var LastName = $('#LastName').val();
var Salary = $('#Salary').val();
if ($("#IsActive").attr('checked', true)) {
var IsActive = 1;
}
else {
var IsActive = 0
}
var newrecord = {
"EmpID": EmpID, "FirstName": FirstName, "LastName": LastName, "Salary": Salary,
};
var senddata = JSON.stringify(newrecord);
jQuery.ajax({
type: "POST",
url: '#Url.Action("Create", "Resource")',
data: JSON.stringify({ "data": senddata }),
datatype: 'json',
contentType: "application/json; charset=utf-8",
success: function (result) {
if (result == true) {
window.location.href = '#Url.Action("ManageResource", "Resource")';
} else {
$("#CreatePopup").html(result);
}
}
});
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(false)
<div class="form-group">
#Html.LabelFor(model => model.EmpID, "Employee ID", new { #class = "control-label col-md-1 col-md-3" })
<div class="col-md-6">
#Html.EditorFor(model => model.EmpID)
#Html.ValidationMessageFor(model => model.EmpID)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FirstName,"First Name", new { #class = "control-label col-md-1 col-md-3" })
<div class="col-md-6">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastName,"Last Name", new { #class = "control-label col-md-1 col-md-3" })
<div class="col-md-6">
#Html.EditorFor(model => model.LastName)
#Html.ValidationMessageFor(model => model.LastName)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-5 col-md-10">
<input type="button" id="CreateResource" onclick="SaveResource()" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
Resource Controller
public PartialViewResult Create(string data)
{
JObject o = JObject.Parse(data);//parsing the json data
tblUser tbluser = new tblUser(); //creating instance for model tblUser
if ((string)o["EmpID"] != "" && (string)o["FirstName"] != "")// if all the required fields are present then add to db
{
db.tblUsers.Add(tbluser);//assign values here
tbluser.EmpID = (int)o["EmpID"];
tbluser.FirstName = (string)o["FirstName"];
tbluser.FirstName = (string)o["FirstName"];
tbluser.LastName = (string)o["LastName"];
tbluser.EmailID = (string)o["EmailID"];
tbluser.Password = (string)o["Password"];
tbluser.RoleID = (int)o["RoleID"];
tbluser.DeptID = (int)o["DeptID"];
tbluser.DesignationID = (int)o["DesignationID"];
tbluser.Salary = (int)o["Salary"];
tbluser.IsActive = (bool)o["IsActive"];
tbluser.CreatedBy = 121;
tbluser.CreatedDate = System.DateTime.Now;
tbluser.UpdatedBy = 121;
tbluser.UpdatedDate = System.DateTime.Now;
db.SaveChanges();
return RedirectToAction("ManageResource");//return to main view when saved
}
else
{
//return with validation summary to partialview popup
return PartialView(tbluser);
}
}
When you load a form using AJAX you need to tell jQuery unobtrusive validation to add the validation data- properties to the form elements. You need to add: $.validator.unobtrusive.parse('#YourFormSelector');
after the .load is completed.
function Create() {
BootstrapDialog.show({
title: "Add Resource",
message: $('<div id="CreatePopup"></div>').load('#Url.Action("Create","Resource")'
, function() {$.validator.unobtrusive.parse('#YourFormSelector');})
});
return false;
}