Asp.Net MVC ajax sends empty object to Controller? - asp.net

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);
}
});
}
}

Related

method for add and update data from popup

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();
}

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):

Why highchart not show me in asp.net?

I'm beginner in asp.net and highchart control,want to use highchart control in my web application web form,for that purpose read this tutorial:
this tutorial
and write this web service in my project:
public class cityPopulation
{
public string city_name { get; set; }
public int population { get; set; }
public string id { get; set; }
}
[WebMethod]
public List<cityPopulation> getCityPopulation(List<string> pData)
{
List<cityPopulation> p = new List<cityPopulation>();
cityPopulation cpData = new cityPopulation();
cpData.city_name = "tabriz";
cpData.population = 100;
p.Add(cpData);
return p;
}
that web service name is this:
WebService1.asmx
and in my web form write this script :
<script type="text/javascript">
function drawPieChart(seriesData) {
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Population percentage city wise'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
name: "Brands",
colorByPoint: true,
data: seriesData
}]
});
}
$("#btnCreatePieChart").on('click', function (e) {
var pData = [];
pData[0] = $("#ddlyear").val();
var jsonData = JSON.stringify({ pData: pData });
$.ajax({
type: "POST",
url: "WebService1.asmx/getCityPopulation",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess_,
error: OnErrorCall_
});
function OnSuccess_(response) {
var aData = response.d;
var arr = []
$.map(aData, function (item, index) {
var i = [item.city_name, item.population];
var obj = {};
obj.name = item.city_name;
obj.y = item.population;
arr.push(obj);
});
var myJsonString = JSON.stringify(arr);
var jsonArray = JSON.parse(JSON.stringify(arr));
drawPieChart(jsonArray);
}
function OnErrorCall_(response) {
alert("Whoops something went wrong!");
}
e.preventDefault();
});
//*
</script>
before that script write this code:
<script src="Scripts/jquery-2.2.3.min.js"></script>
<script src="Scripts/Highcharts-4.0.1/js/highcharts.js"></script>
and write this html code:
<select id="ddlyear">
<option>2010</option>
<option>2011</option>
<option>2012</option>
<option>2013</option>
<option>2014</option>
<option>2015</option>
</select>
<button id="btnCreatePieChart">Show </button>
<br />
<div>
<div id="container" style="width: 500px; height: 500px"></div>
</div>
but when i run project and fire the button,can not see anything,and chart not show to me,what happen?is my code incorrect?how can i solve that problem?thanks.
i think ajax can not call the web service!

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

jquery in visual studio 2012 ultimate and mvc 3

i need to ask something and i am getting stucked of this:
This is my controller code :
public ActionResult FastRegister(FormCollection collection)
{
UserModel db = new UserModel(0);
string str = "";
//Boolean
//Common.IsAlphaNumeric_Dot_Underscore()? er
errorInsert err = new errorInsert();
try
{
db.set_value(0, Common.HtmlFormUrlEncode(collection["user_name"]), Common.HtmlFormUrlEncode(collection["user_pass"]), "", "", Common.HtmlFormUrlEncode(collection["user_email"]), "", DateTime.Now, "", Common.RandomString(false), 0);
db.Insert();
err.duplicate = false;
err.error = "success register";
return Json(err, JsonRequestBehavior.AllowGet);
}
catch (Exception exception)
{
if (exception.Message.Contains("unique") == true && exception.Message.Contains("duplicate") == true)
{
err.duplicate = true;
err.error = "username or email already taken";
}
else
{
err.duplicate = false;
err.error = exception.Message;
}
return Json(err, JsonRequestBehavior.AllowGet);
}
}
}
class errorInsert
{
public Boolean duplicate;
public string error;
public errorInsert()
{
}
}
and this is my jquery code :
<script type="text/javascript">
$(document).ready(function(){
function ajax_send_url(user_name, user_pass, user_email)
{
$.ajax({
type: 'POST',
url: 'http://localhost/smile/User/FastRegister',
data: 'user_name='+user_name+'&user_pass='+user_pass+'&user_email='+user_email,
//contentType: 'application/json; charset=utf-8',
success: function(e)
{
//var x=jQuery.parseJSON(e);
$("#loading").html(e.error);
}
, dataType:"json"
, beforeSend:function (e){$("#loading").html('<img src="loading.gif" width="50px">');}
});
}
$("#register").click
(
function()
{
var user_name = $("#user_name").val();
var user_pass = $("#user_pass").val();
var user_email = $("#user_email").val();
ajax_send_url(user_name,user_pass,user_email );
}
);
});
I've got in my firebug 200 OK Http but no response when i checked. Please someone figure it out and help me. Thanx...

Resources