method for add and update data from popup - asp.net

I have a pop up form from which new data can be added or old data can be updated.
But I don't know how to write method for this condition. I mean in the case of new data entry I don't need the Id but in case of edit I need the Id attribute. The controller name is Vehicle.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddorEdit([Bind(Include = "Id,VehicleType,Amount,RenewPeriod,Status")] Vehicle vehicle)
{
vehicle.RegisteredDate = DateTime.Now;
vehicle.RegisteredBy = "admin";
if (ModelState.IsValid)
{
db.Vehicle.Add(vehicle);
db.SaveChanges();
}
return Json(new { success = true, message = "Saved Successfully" }, JsonRequestBehavior.AllowGet);
}
The jquery code of index page from where pop up is called ::
<a class="btn btn-success" style="margin-bottom:10px;" onclick="PopupForm('#Url.Action("AddorEdit", "Vehicles")')"><i class="fa fa-plus"></i> Add New</a>
<script>
var Popup, dataTable;
$(document).ready(function () {
dataTable = $("#tbl_vehicle").DataTable({
"ajax":{
"url": "/Vehicles/GetVehicle",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "VehicleType" },
{ "data": "Amount" },
{ "data": "RenewPeriod" },
{ "data": "RegisteredDate" },
{ "data": "RegisteredBy" },
{ "data": "Status" },
{ "data": "ModifiedBy" },
{ "data": "ModifiedDate" }
],
"language": {
"emptyTable" : "No data available, please click on <b>Add</b> button"
}
});
});
function PopupForm(url) {
var formDiv = $('<div/>');
$.get(url).done(function (response) {
formDiv.html(response);
Popup = formDiv.dialog({
autoOpen: true,
resizable: false,
title: 'fill details',
height: 500,
width: 700,
close: function () {
Popup.dialog('destroy').remove();
}
});
});
}
function SubmitForm(form) {
alert("testing....");
$.ajax({
type: "POST",
url: form.action,
data: $(form).serialize(),
success: function (date) {
if(data.success)
{
Popup.dialog('close');
dataTable.ajax.reload();
}
}
});
return false;
}
</script>

An easy way to handle this by making id as a HiddenField so when ever user post data to the server you can query the id field.
whether it has value or not and decide which operation you should perform i.e. Add operation if id is null/empty and Edit Operation if Id has the value.
Please use below code section for reference :
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddorEdit([Bind(Include = "Id,VehicleType,Amount,RenewPeriod,Status")] Vehicle vehicle)
{
if (ModelState.IsValid)
{
if(vehicle.Id <= 0)
{
vehicle.RegisteredDate = DateTime.Now;
vehicle.RegisteredBy = "admin";
db.Vehicle.Add(vehicle);
}
else
{
db.Entry(vehicle).State = EntityState.Modified;
//perform more checks if you want
}
db.SaveChanges();
}
return Json(new { success = true, message = "Saved Successfully" }, JsonRequestBehavior.AllowGet);
}

You can achieve it by this simple way
if (ModelState.IsValid)
{
if(vehicle.Id <= 0)
{
vehicle.RegisteredDate = DateTime.Now;
vehicle.RegisteredBy = "admin";
db.Vehicle.Add(vehicle);
}
else
db.Entry(vehicle).State = EntityState.Modified;
db.SaveChanges();
}

Related

Asp.Net MVC ajax sends empty object to Controller?

I am working on a survey application with Asp.Net MVC.
I have a page named Index.cshtml which has a question table and a 'Add New' button.Once button clicked, a popup is opened with jQuery. I am calling a view from controller to fill jQuery dialog named as AddOrEdit.cshtml (child page). I am adding new question and options. Question is a textfield and its options are added in editable table. Once clicked submit button, Submit form event (save or update) is fired. Asp.Net MVC ajax sends empty object to Controller. My Question object has Option list.So one-to-many relation.
Index.cshtml and submit(ajax) function
#{
ViewBag.Title = "Soru Listesi";
}
<h2>Soru Oluşturma</h2>
<a class="btn btn-success" style="margin-bottom: 10px"
onclick="PopupForm('#Url.Action("AddOrEdit","Question")')"><i class="fa fa-plus"></i> Yeni Soru
Oluştur</a>
<table id="questionTable" class="table table-striped table-bordered accent-blue" style="width:
100%">
<thead>
<tr>
<th>Soru No</th>
<th>Soru Adı</th>
<th>Oluşturma Tarihi</th>
<th>Güncelleme Tarihi</th>
<th>Güncelle/Sil</th>
</tr>
</thead>
</table>
<link href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
#section Scripts{
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
<script>
var Popup, dataTable;
$(document).ready(function() {
dataTable = $("#questionTable").DataTable({
"ajax": {
"url": "/Question/GetData",
"type": "GET",
"datatype": "json"
},
"columnDefs": [
{ targets: 2 }
],
"scrollX": true,
"scrollY": "auto",
"columns": [
{ "data": "QuestionId" },
{ "data": "QuestionName" },
{
"data": "CreatedDate",
"render": function(data) { return getDateString(data); }
},
{
"data": "UpdatedDate",
"render": function(data) { return getDateString(data); }
},
{
"data": "QuestionId",
"render": function(data) {
return "<a class='btn btn-primary btn-sm' onclick=PopupForm('#Url.Action("AddOrEdit", "Question")/" +
data +
"')><i class='fa fa-pencil'></i> Güncelle</a><a class='btn btn-danger btn-sm' style='margin-left:5px' onclick=Delete(" +
data +
")><i class='fa fa-trash'></i> Sil</a>";
},
"orderable": false,
"searchable": false,
"width": "150px"
}
],
"language": {
"emptyTable":
"Soru bulunamadı, lütfen <b>Yeni Soru Oluştur</b> butonuna tıklayarak yeni soru oluşturunuz. "
}
});
});
function getDateString(date) {
var dateObj = new Date(parseInt(date.substr(6)));
let year = dateObj.getFullYear();
let month = (1 + dateObj.getMonth()).toString().padStart(2, '0');
let day = dateObj.getDate().toString().padStart(2, '0');
return day + '/' + month + '/' + year;
};
function PopupForm(url) {
var formDiv = $('<div/>');
$.get(url)
.done(function(response) {
formDiv.html(response);
Popup = formDiv.dialog({
autoOpen: true,
resizable: true,
title: 'Soru Detay',
modal: true,
height: 'auto',
width: '700',
close: function() {
Popup.dialog('destroy').remove();
}
});
});
}
function SubmitForm(form) {
event.preventDefault();
if (form.checkValidity() === false) {
event.stopPropagation();
}
form.classList.add('was-validated');
if ($(form).valid()) {
var question = {};
question.questionId = 1111;
var options = new Array();
$("#questionForm TBODY TR").each(function() {
var row = $(this);
var option = {};
option.OptionId = row.find("TD").eq(0).html();
option.OptionName = row.find("TD").eq(1).html();
options.push(option);
});
question.options = options;
question.responses = new Array();
$.ajax({
type: "POST",
url: form.action,
data: JSON.stringify(question),
success: function(data) {
if (data.success) {
debugger;
Popup.dialog('close');
//dataTable.ajax.reload();
$.notify(data.message,
{
globalPosition: "top center",
className: "success",
showAnimation: "slideDown",
gap: 1000
});
}
},
error: function(req, err) {
debugger;
alert('req : ' + req + ' err : ' + err);
},
complete: function(data) {
alert('complete : ' + data.status);
}
});
}
}
function ResetForm(form) {
Popup.dialog('close');
return false;
}
function Delete(id) {
if (confirm('Bu soruyu silmek istediğinizden emin misiniz?')) {
$.ajax({
type: "POST",
url: '#Url.Action("Delete", "Question")/' + id,
success: function(data) {
if (data.success) {
dataTable.ajax.reload();
$.notify(data.message,
{
className: "success",
globalPosition: "top center",
title: "BAŞARILI"
})
}
}
});
}
}
</script>
}
QuestionController AddOrEdit action
[HttpPost]
public ActionResult AddOrEdit(Questions question)
{
using (MerinosSurveyEntities db = new MerinosSurveyEntities())
{
List<Options> options = (List<Options>) question.Options;
List<Options> existingOptions = new List<Options>(db.Options.Where(x => x.Status && x.IsActive && x.QuestionId == question.QuestionId));
foreach (Options existingOption in existingOptions)
{
Options optionUpdated = options.FirstOrDefault(x => x.OptionId == existingOption.OptionId);
if (optionUpdated != null)
{
//Update
existingOption.UpdatedDate = DateTime.Now;
existingOption.OptionName = optionUpdated.OptionName;
existingOption.IsActive = true;
existingOption.Status = true;
db.Options.Attach(existingOption);
db.Entry(existingOption).State = EntityState.Modified;
db.SaveChanges();
options.RemoveAll(x => x.OptionId == existingOption.OptionId);
}
else
{
//Delete
existingOption.Status = false;
existingOption.UpdatedDate = DateTime.Now;
db.Options.Attach(existingOption);
db.Entry(existingOption).State = EntityState.Modified;
db.SaveChanges();
}
}
foreach (Options optionNew in existingOptions)
{
optionNew.IsActive = true;
optionNew.Status = true;
optionNew.CreatedDate = DateTime.Now;
optionNew.UpdatedDate = DateTime.Now;
db.Options.Add(optionNew);
db.SaveChanges();
return Json(new { success = true, message = "Soru ve seçenekleri başarılı şekilde oluşturuldu/güncellendi." }, JsonRequestBehavior.AllowGet);
}
// db.Questions.Attach(question);
return Json(new { success = true, message = "Soru başarılı bir şekilde güncellendi." }, JsonRequestBehavior.AllowGet);
}
}
Question object
//------------------------------------------------------------------------------
// <auto-generated>
//------------------------------------------------------------------------------
namespace MerinosSurvey.Models
{
using System;
using System.Collections.Generic;
public partial class Questions
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Questions()
{
this.Responses = new HashSet<Responses>();
this.Options = new HashSet<Options>();
}
public int QuestionId { get; set; }
public string QuestionName { get; set; }
public int QuestionTypeId { get; set; }
public System.DateTime CreatedDate { get; set; }
public int CreatedUserId { get; set; }
public bool IsActive { get; set; }
public bool Status { get; set; }
public System.DateTime UpdatedDate { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Responses> Responses { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Options> Options { get; set; }
}
}
Option class
//------------------------------------------------------------------------------
// <auto-generated>
//------------------------------------------------------------------------------
namespace MerinosSurvey.Models
{
using System;
using System.Collections.Generic;
public partial class Options
{
public int OptionId { get; set; }
public string OptionName { get; set; }
public int QuestionId { get; set; }
public System.DateTime CreatedDate { get; set; }
public System.DateTime UpdatedDate { get; set; }
public bool IsActive { get; set; }
public bool Status { get; set; }
public virtual Questions Questions { get; set; }
}
}
I finally solved the problem. Because I forgot to add 'contentType' to the section where I sent an ajax request, 'ajax' was sending empty objects to the controller. But both Pascal case and camel case I tried with the result has not changed. I've seen Ajax work independently in Case.
I'm adding the section I'm editing. In this case, it works without problems.
function SubmitForm(form) {
event.preventDefault();
if (form.checkValidity() === false) {
event.stopPropagation();
}
form.classList.add('was-validated');
if ($(form).valid()) {
var question = {};
question.questionId = 1111;
question.questionName = "Name";
var options = new Array();
$("#questionForm TBODY TR").each(function() {
var row = $(this);
var option = {};
option.optionId = row.find("TD").eq(0).html();
option.optionName = row.find("TD").eq(1).html();
option.questionId = 0;
option.isActive = true;
option.status = true;
options.push(option);
});
question.options = options;
question.responses = new Array();
$.ajax({
type: "POST",
url: form.action,
data: JSON.stringify(question),
contentType: "application/json",//this is the line I forgot to add.
success: function(data) {
if (data.success) {
debugger;
Popup.dialog('close');
//dataTable.ajax.reload();
$.notify(data.message,
{
globalPosition: "top center",
className: "success",
showAnimation: "slideDown",
gap: 1000
});
}
},
error: function(req, err) {
debugger;
alert('req : ' + req + ' err : ' + err);
},
complete: function(data) {
alert('complete : ' + data.status);
}
});
}
}

Async Controller Progress Request Pending in MVC

I'm trying to get the percentage of Ajax requests processed at Mvc. I learned that this should be done with AsyncController.
But when the first request worked, I did not get the percentage because it was on the TaskProgress tail.
Controller:
public class AsyncTestController : AsyncController
{
public void TaskAsync(int id)
{
AsyncManager.OutstandingOperations.Increment();
Task.Factory.StartNew(taskId =>
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(200);
HttpContext.Application["task" + taskId] = i;
}
var result = "result";
AsyncManager.OutstandingOperations.Decrement();
AsyncManager.Parameters["result"] = result;
return result;
}, id);
}
public ActionResult TaskCompleted(string result)
{
return Content(result, "text/plain");
}
public ActionResult TaskProgress(int id)
{
string asd = HttpContext.Application["task" + id].ToString();
return Json(new
{
Progress = HttpContext.Application["task" + id]
}, JsonRequestBehavior.AllowGet);
}
}
View (javascript):
function async_test_start() {
var taskId = 543;
$.ajax({
url: '#Url.Content("~/IK/AsyncTest/task/")',
data: { id: taskId },
type: "GET",
async: true,
success: function (dt) {
window.clearInterval(intervalId);
console.log(dt);
}
});
var intervalId = window.setInterval(function () {
$.ajax({
url: '#Url.Content("~/IK/AsyncTest/taskprogress/")',
data: { id: taskId },
type: "GET",
async: true,
success: function (dt) {
console.log(dt.Progress + '%');
}
});
}, 5000);
}
Result (when ajax request starts):

Script not works (ASP.NET MVC)

I have script for recording video
Here is code of it
var fileName;
stop.onclick = function () {
record.disabled = false;
stop.disabled = true;
window.onbeforeunload = null; //Solve trouble with deleting video
preview.src = '';
fileName = Math.round(Math.random() * 99999999) + 99999999;
console.log(fileName);
var full_url = document.URL; // Get current url
var url_array = full_url.split('/') // Split the string into an array with / as separator
var id = url_array[url_array.length - 1]; // Get the last part of the array (-1)
function save() {
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
link: fileName,
id: id,
},
url: '#Url.Action("LinkWriter", "Interwier")',
success: function (da) {
if (da.Result === "Success") {
alert("lol");
} else {
alert('Error' + da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}
I try to get url with this row var id = url_array[url_array.length - 1]; // Get the last part of the array (-1)
and with this code write to table filename
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
link: fileName,
id: id,
},
url: '#Url.Action("LinkWriter", "Interwier")',
success: function (da) {
if (da.Result === "Success") {
alert("lol");
} else {
alert('Error' + da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}
but it not works.
There is my Action method for it
[HttpPost]
public ActionResult LinkWriter(string link, int id) {
Link link_ = new Link
{
Link1 = link,
Interwier_Id = id,
};
db.Link.Add(link_);
db.SaveChanges();
return View();
}
But it not works. Where is my mistake?
UPDATE
As I understood not works this
function save() {
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
link: fileName,
id: id,
},
url: '#Url.Action("LinkWriter", "Interwier")',
success: function (da) {
if (da.Result === "Success") {
alert("lol");
} else {
alert('Error' + da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}

MVC4 Detailview from GridMvc.selectedData

I am trying to get the selected row of a MVCGrid and display the details in an modal dialog using a partialview.
I am getting the selected row via ajax:
$(document).ready(function(){
var selectedRow;
$(document).on('click', '.grid-mvc', function () {
pageGrids.PersonGrid.onRowSelect(function (e) {
// $.prompt(e.row.ID);
SendData(e.row);
});
});
});
The 'SendData'-function is:
function SendData(i) {
var data= i.ID;
$.ajax({
url: '/Home/Person',
contentType: "application/html; charset=utf-8",
type: "GET",
data: { "id": daten },
dataType: "html"
, success: function () {
ShowPersonDetails(data);
}
});
}
and the ShowPersonDetails(data) is like that:
function ShowPersonDetails(data) {
$(document).ready(function () {
$('#PersonDiv').load("Person?id=" + data);
$("#PersonDiv").prompt(
$("#PersonDiv").html(),
{
title: "some title",
buttons: { OK: 'true', Abbruch: 'false' },
position: { width: 800, height: 600 }
});
});
}
The controller:
[HttpGet]
public ActionResult Person(int id)
{
var pS = new DbAccess(MvcApplication.Connection).GetUserData(id);
var p = new Person();
if (pS.Rows.Count < 0)
{
return PartialView("Person");
}
p.Alter = pS.Rows[0].ItemArray[0].ToString();
p.Nachname = pS.Rows[0].ItemArray[5].ToString();
return PartialView("Person", p);
}
Any advice would be nice!
Greetings
PP
i did something like you are trying to do, so hope my code helps
in the grid, table, i put a link for details
<tr>
<td>
#Html.ActionLink("Details", "ActionDetails", new { id = Model.LstItems[x].ID }, new { #class = "detailsLink" })
</td>
</tr>
the javascript
$('#detailsDialog').dialog({
autoOpen: false,
width: 400,
resizable: false,
modal: true,
buttons: {
"Cancel": function () {
$(this).dialog("close");
}
}
});
$(".detailsLink").button();
$(".detailsLink").click(function () {
linkObj = $(this);
var dialogDiv = $('#detailsDialog');
var viewUrl = linkObj.attr('href');
$.get(viewUrl, function (data) {
dialogDiv.html(data);
//open dialog
dialogDiv.dialog('open');
});
return false;
});
in somewhere in the view
<div id="detailsDialog" title="Offer Details">
</div>
the controller
public ActionResult ActionDetails(int id)
{
ItemEntity model = ItemEntity .GetBy(id);
return PartialView(model);
}
the partial view
#model YourNameSpace.Entities.ItemEntity
#using (Ajax.BeginForm("ActionDetails", "YourController", new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
OnSuccess = "updateSuccess",
OnFailure = "showErrorMessage"
}, new { #id = "detailForm" }))
{
//your details for your item
}
hope this help you

MVC3 JSON Return to Edit Page

So I have some javascript code that sends data to my controller:
Javascript:
<script type="text/javascript">
$(document).ready(function () {
$("#newGrade").click(function () {
var newGradeName = $("#newGradeName").val();
var newGradeValue = $("#newGradeValue").val();
var vSchoolID = $("#SchoolID").val();
if (newGradeName != null && newGradeValue != null) {
$.ajax({
url: '#Url.Action("NewGrade", "School")',
data: { gradeName: newGradeName, gradeValue: newGradeValue, schoolID: vSchoolID },
type: 'POST',
traditional: true,
success: function (data) {
if (data.status)
window.location = data.route;
},
error: function () {
return false;
}
});
}
});
});
</script>
Controller:
public ActionResult NewGrade(String gradeName, Int32 gradeValue, Guid schoolID)
{
School school = schoolRepository.GetByID(schoolID);
school.Grades.Add(
new Grade
{
GradeID = Guid.NewGuid(),
Name = gradeName,
NumericalValue = gradeValue
});
schoolRepository.Update(school);
schoolRepository.Save();
if (Request.IsAjaxRequest())
{
var json = new { status = true, route = Url.RouteUrl(new { action = "Edit", id = schoolID }) };
return Json(json, JsonRequestBehavior.AllowGet);
}
return View();
}
My issue now is I want to return to my Edit page (possibly refreshing the page, but not the data, or just refresh the entire page), but my Edit page takes an ID (schoolID). Shown here when pressing the button to get to the Edit page:
<i class="icon-pencil"></i> Edit
Try window.location.href and see what happens.
success: function(data) {
if (data.status)
window.location.href = data.route;
},
This should work fine assuming you are getting a JSON reponse from your action method like
{"status":"true","route":"/School/Edit/1"}
where 1 is the ID of new record.

Resources