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")
}
Related
I build this code for select all checboxes and pass to controller, I using button when click it check all checkboxes and pick up all variables like (idtip, idemployee) trought array send to controller to update database table.
<tr>
<th>name</th>
<th>tips</th>
<th>
<button id="btnClick" class="btnClick">Select all</button>
</th>
</tr>
Here is my input and script.
#foreach (var item in (IEnumerable<cit.Models.getCheIdTip_Result>)Model)
{
<tr>
<td>#item.idtip</td>
<td>#item.tipname</td>
<td>
<div class="pure-checkbox" idtip="#item.idtip">
<input type="checkbox" idtip="#item.idtip" class="checktip"
checked="#(item.idemployee == ViewBag.idemployee ? true : false)"
name="#item.id.ToString()" id="#item.id.ToString()" />
<label for="#item.id.ToString()"></label>
</div>
</td>
</tr>
}
</table>
<input type="hidden" value="#ViewData["idemployee"]" name="idemployee" id="idemployee" class="idemployee" />
<script>
$('.pure-checkbox').click(function () {
$(this).parents('td').toggleClass('chked')
})
var wantedids = [idemployee,idtip]
$("#btnClick").click(function () {
for (var i = 0; i < $('.pure-checkbox').length; i++) {
if ($('.pure-checkbox').eq(i).parents('td').hasClass('chked')) {
wantedids.push(
$('.pure-checkbox').eq(i).attr('idtip')
)
}
}
$.post("UrlSettingsDocument.Tips", { ids: wantedids },
)
})
I using button when click it check all checkboxes and pick up all
variables like (idtip, idemployee) trought array send to controller to
update database table.
You could refer the following sample code:
Create a ViewModel to display records:
public class TestViewModel
{
public int id { get; set; }
public int idtip { get; set; }
public string idemployee { get; set; }
public bool isChecked { get; set; }
}
In the Controller, add the following actions:
//Set the initial data and return to view.
public IActionResult Default()
{
List<TestViewModel> items = new List<TestViewModel>()
{
new TestViewModel(){ id=101, idtip=1001, idemployee="AAA" },
new TestViewModel(){id=102,idtip=1002, idemployee="BBB" },
new TestViewModel(){id=103, idtip=1003, idemployee="CCC" },
new TestViewModel(){ id=104,idtip=1004, idemployee="DDD" },
new TestViewModel(){id=105, idtip=1005, idemployee="EEE" }
};
ViewBag.idemployee = "CCC"; //set the default checked item.
return View(items);
}
public IActionResult AddItems(IEnumerable<TestViewModel> items)
{
//insert the items into database.
return Ok("OK");
}
Then, in the View page (Default.cshtml), using the following code to display the content:
Here we can use a select all checkbox, after checking it, will select all items.
#model IEnumerable<WebApplication.Models.TestViewModel>
#{
ViewData["Title"] = "Default";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<table class="table">
<thead>
<tr>
<th>
<input type="checkbox" id="btnSelectAll" class="btnClick" /> <label for="btnSelectAll">Select All</label>
</th>
<th>
#Html.DisplayNameFor(model => model.idtip)
</th>
<th>
#Html.DisplayNameFor(model => model.idemployee)
</th>
<th>
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model) {
<tr>
<td>
<div class="pure-checkbox" idtip="#item.idtip">
<input type="checkbox" idtip="#item.idtip" data-idemployee="#item.idemployee" class="checktip"
checked="#(item.idemployee == ViewBag.idemployee ? true : false)"
name="#item.id.ToString()" id="#item.id.ToString()" />
<label for="#item.id.ToString()"></label>
</div>
</td>
<td>
#Html.DisplayFor(modelItem => item.idtip)
</td>
<td>
#Html.DisplayFor(modelItem => item.idemployee)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</tbody>
</table>
<button id="btnSubmit" class="btnClick">Submit</button>
At the end of the Default.cshtml page, using the following script to achieve the select all function and submit the records to the controller.
#section Scripts{
<script>
$(function () {
//If checked the select all checkbox, select all items. else unchecked.
$("#btnSelectAll").click(function () {
if ($(this).is(":checked")) {
$(".checktip").each(function (index, item) {
$(item).prop("checked", true);
});
}
else {
$(".checktip").each(function (index, item) {
$(item).prop("checked", false);
});
}
});
$("#btnSubmit").click(function () {
var testViewModels = [];
//using the class selector to loop through the checkbox list and get all items, if you want to get the checked items, add an if...else statement in the each function.
$(".checktip").each(function (index, item) {
var TestViewModel = {};
TestViewModel.idtip = $(this).attr("idtip");
TestViewModel.idemployee = $(this).attr("data-idemployee");
TestViewModel.isChecked = $(this).is(":checked");
testViewModels.push(TestViewModel);
});
$.ajax({
type: "Post",
url: "/Home/AddItems", //remember change the controller to your owns.
data: { items: testViewModels }, //the name ("items") should be the same with the parameter's name in the controller.
success: function (data) {
console.log(data)
},
error: function (response) {
console.log(response.responseText);
}
});
});
});
</script>
}
The result as below:
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 have a normal index page where the list of the contents in the database are displayed. I have a create button in my Index which as of now redirects to another page to Create a new item.
First I tried partial Views to get it working but the page still redirected to another page with no layout. Then I tried using Jquery to hide/show div that contains the HTML code for Create. But I could not post the value to the correct Action method.
I am not having all that I have tried so far. I suppose my Index View wouldn't be of great interest.
Index View when using Jquery
<div> Displaying the index View</div>
<div id="Create" style="display:none">
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.LabelFor(model => model.LsystemFamily.FamilyName, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.LsystemFamily.FamilyName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LsystemFamily.FamilyName, "", new { #class = "text-danger" })
#Html.LabelFor(model => model.LsystemFamily.DescriptionEN, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.LsystemFamily.DescriptionEN, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LsystemFamily.DescriptionEN, "", new { #class = "text-danger" })
#Html.LabelFor(model => model.LsystemFamily.DescriptionDE, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.LsystemFamily.DescriptionDE, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LsystemFamily.DescriptionDE, "", new { #class = "text-danger" })
<input type="submit" value="Create" class="btn btn-default" />
}
Jquery
<script type="text/javascript">
$(document).ready(function () {
$('#btn').click(function () {
$('#Create').toggle();
});
});
</script>
Controller (when returning Partial View)
public ActionResult Create()
{
return View("_Create");
}
Index View when returning Partial View
<div>
Index View
#Html.ActionLink("Create","Create","Controller");
</div>
#Html.Partial("_Create")
In none of the cases I had my Create displaying the way I wanted.
Based on the Answers I have tried to add the partial View and then toggle the div. but i get the following error
An exception of type 'System.InvalidOperationException' occurred in
System.Web.Mvc.dll but was not handled in user code
Additional information: The model item passed into the dictionary is
of type
'System.Data.Entity.Infrastructure.DbQuery`1[TEDALS_Ver01.Models.LsystemFamily]',
but this dictionary requires a model item of type
'TEDALS_Ver01.Models.LsystemFamily'.
Update : Index View
#using (Html.BeginForm())
{
<p>
Search #Html.TextBox("SearchString")
<input type="submit" class="btn btn-default" value="Search" />
</p>
}
<script type="text/javascript">
$(document).ready(function () {
$('#btn').click(function () {
$('#Create').toggle();
});
});
</script>
<table class="table">
<tr>
<th>
Family Name
</th>
<th>
System Count
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td data-toggle="tooltip" title="#item.DescriptionDE" data-placement="right">
#Html.ActionLink(item.FamilyName, "ViewSystems", "LsystemFamilies", new { id = #item.LsystemFamilyID},null)
</td>
<td data-toggle="tooltip" title="Number of Systems in #item.FamilyName" data-placement="right">
#Html.DisplayFor(modelItem => item.LsystemCount)
</td>
<td>
#*#Html.ActionLink("Add System", "Create", "Lsystems", new { id = item.LsystemFamilyID }, null)|*#
#Html.ActionLink("Edit", "Edit", new { id = item.LsystemFamilyID }) |
#Html.ActionLink("Details", "Details", new { id = item.LsystemFamilyID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.LsystemFamilyID })|
</td>
</tr>
}
</table>
<input type="button" id="btn" class="btn btn-default" value="Create">
</div>
<div id="Create" style="display:none">
#Html.Partial("_Create")
</div>
#section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$('#btn').click(function () {
$('#Create').toggle();
});
});
</script>
#Scripts.Render("~/bundles/jqueryval")
}
UPDATE: Create Post method
public ActionResult Create([Bind(Include = "LsystemFamilyID,FamilyName,LsystemCount,DescriptionEN,DescriptionDE,CreatedOn,ModifiedOn,CreatedBy,ModifiedBy")] LsystemFamily lsystemFamily)
{
lsystemFamily.CreatedOn = DateTime.Now;
lsystemFamily.CreatedBy = User.Identity.Name;
lsystemFamily.ModifiedOn = DateTime.Now;
lsystemFamily.ModifiedBy = User.Identity.Name;
lsystemFamily.LsystemCount = 0;
if (ModelState.IsValid)
{
if (db.LsystemFamily.Any(x => x.FamilyName.Equals(lsystemFamily.FamilyName)))
{
ModelState.AddModelError("FamilyName", "Family Name already Exists");
return PartialView("_Create",lsystemFamily);
}
db.LsystemFamily.Add(lsystemFamily);
db.SaveChanges();
return RedirectToAction("Index");
}
return PartialView("_Create",lsystemFamily);
}
What you exactly want to do, I mean if you want to show Create from on a button click then just create a partail view with Layout = null i.e "_Create" ( no need an action for it), now just render this partial view in the div that you are toggling:
<div id="Create" style="display:none">
#Html.Partial("_Create")
</div>
and on the submission of create request if you want to refresh your index page then either you can user Ajax.BeginForm in _create view or you can post it by jquery ajax.
<script type="text/javascript">
$(document).ready(function () {
$('#btn').click(function () {
$('#Create').toggle();
});
});
</script>
You are trying to access #btn by ID, but you set it as class.btn is a class name.So JQuery can't find your button.Do like this
<script type="text/javascript">
$(document).ready(function () {
$('.btn').click(function () {
$('#Create').toggle();
});
});
</script>
I am using asp.net MVC 5.
In Bootbox js
$(document).on("click", ".MyLink", function (e) {
bootbox.confirm("Are you sure?", function(result) {
Example.show("Confirm result: "+result);
});
});
#Html.ActionLink("Delete", "Delete", new { id = item.CustomerID }, new { #class = "MyLink" })
How to delete the HTML action link ?
Please find the full details of the code:-
Javascript code:-
<script src="~/Scripts/bootbox.min.js"></script>
$(document).on("click", ".MyLink", function (e) {
var self = this;
bootbox.confirm("Are you sure?", function (result) {
Example.show("Confirm result: " + result);
$(self).remove();
});
});
HTML Code:-
<h2>Index</h2>
<p>Content here. <a class="MyLink" href=#>Alert!</a></p>
<p>
#Html.ActionLink("Create New", "Create")
</p>
Also see the inside<table> code for your
reference:-
<table class="table">
<tr>
<th> First Name </th>
<th> Last Name </th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td> #Html.DisplayFor(modelItem => item.FirstName) </td>
<td> #Html.DisplayFor(modelItem => item.LastName) </td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.CustomerID }) |
#Html.ActionLink("Details", "Details", new { id = item.CustomerID }) |
#*#Html.ActionLink("Delete", "Delete", new { id = item.CustomerID, #class = "MyLink" })*#
Delete
</td>
</tr>
}
Also see the Controller code for your reference:-
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Customer customer = db.Customers.Find(id);
db.Customers.Remove(customer);
db.SaveChanges();
if (customer == null)
{
return HttpNotFound();
}
return RedirectToAction("Index");
//return View(customer);
}