Send data from textbox with ajax to asp.net mvc 5 controller - javascript

I need some help. I write little app using ASP.NET MVC5 with JavaScript, jQuery, Ajax... and I can't send data from javascript to MVC Controller and change the model.
ViewModel
public class MyViewModel
{
//...
public string SearchString { get; set; }
public int? FirstInt { get; set; }
public int? SecondInt { get; set; }
}
Javascript
function keystroke() {
var a = 0, b = 0;
$('#search').keyup(function (event) { a = 1; });
$('#search').keydown(function (event) { b = 1; });
$("#search").keypress(function (event) {
if (e.which === 13) {
e.preventDefault();
$('form').click(function () {
sendForm(a, b);
});
}
});
};
function sendForm(a, b) {
$.ajax({
url: #Url.Action("Index", "Home"),
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
FirstInt: a,
SecondInt: b
}),
success: function () {
alert('success');
}
});
};
View
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { #class = "form-inline", role = "form" }))
{
<div class="form-group has-feedback">
#Html.TextBox("SearchString", ViewBag.SearchFilter as string, new
{
#class = "form-control",
onclick="keystroke()",
id = "search"
})
</div>
}
Controller
public async Task<ActionResult> Index(MyViewModel model)
{
//...
if (model.SearchString != null)
{
//...
var a = model.FirstInt;
var b = model.SecondInt;
}
//...
return View(model);
}
Help me, please, to send all the values to controller. Those that changed in JavaScript and what I enter in the textbox. Thanks.

Javascript Code:
function keystroke() {
var a = 0, b = 0;
$('#search').keyup(function (event) { a = 1; });
$('#search').keydown(function (event) { b = 1; });
$("#search").keypress(function (event) {
if (e.which === 13) {
e.preventDefault();
$('form').click(function () {
var text = $("#search").val()
sendForm(a, b, text);
return false;
});
}
});
};
function sendForm(a, b, text) {
var data = {FirstInt: a,SecondInt: b,SearchString: text}
$.ajax({
url: 'Home/Index',
type: 'POST',
contentType: 'application/json',
data: data,
success: function () {
alert('success');
}
});
};
Controller Code
[HttpPost]
public async Task<ActionResult> Index(MyViewModel model)
{
//...
if (model.SearchString != null)
{
//...
var a = model.FirstInt;
var b = model.SecondInt;
}
//...
return View(model);
}

Related

Passing Javascript Object array to MVC Controller

I have these ViewModels:
public class UserAddRoleListViewModel
{
public String Id { get; set; }
public String Name { get; set; }
}
public class SaveUserNewRoleViewModel
{
[Required]
public String RoleId { get; set; }
public String RoleName { get; set; }
public List<UserAddRoleListViewModel> RoleList { get; set; }
}
How can I pass an array of objects that have a format like this:
var object = {
Id: rowIdItem,
Name: rowItem
};
dataSet.push(object);
to my MVC Controller here:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult VerifyRole(SaveUserNewRoleViewModel Input)
{
IEnumerable<object> errors = null;
if (ModelState.IsValid)
{
if(Input.RoleList[0] != null)
{
foreach (var item in Input.RoleList)
{
if (Input.RoleId == item.Id)
{
ModelState.AddModelError("RoleId", "Role already exists");
errors = AjaxError.Render(this);
return Json(new { success = false, errors });
}
}
return Json(new { success = true });
}
return Json(new { success = true });
}
else
{
errors = AjaxError.Render(this);
return Json(new { success = false, errors });
}
}
So far it seems like its always passing an nothing when I debug it
EDIT:
Just to clarify. I can already pass the item via ajax. It's just that when I debug, RoleList is empty.
This is my ajax function:
$(document).on("submit", "#modal", function (e) {
e.preventDefault();
var selectedText = $("##Html.IdFor(m=>m.RoleId) :selected").text();
var selectedId = $("##Html.IdFor(m=>m.RoleId)").val();
var form_data = $(this).serializeArray();
form_data.push({ name: "RoleList", value: dataSet });
console.log(form_data);
rowIdItem = selectedId;
rowItem = selectedText;
$("#close").trigger("click");
$.ajax({
url: "#Url.Action("VerifyRole", #ViewContext.RouteData.Values["controller"].ToString())",
method: "POST",
data: form_data,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function (result) {
if (result.success) {
rowIdItem = selectedId;
rowItem = selectedText;
$("#close").trigger("click");
return;
}
$.each(result.errors, function (index, item) {
// Get message placeholder
var element = $('[data-valmsg-for="' + item.propertyName + '"]');
element.empty();
// Update message
element.append($('<span></span>').text(item.errorMessage));
// Update class names
element.removeClass('field-validation-valid').addClass('field-validation-error');
$('#' + item.propertyName).removeClass('valid').addClass('input-validation-error');
});
}
});
return false;
});
EDIT 2:
Added code that fills dataSet:
$(document).on($.modal.AFTER_CLOSE, function (event, modal) {
dataSet.push(object);
table.row.add(object).draw();
$("#modal").empty();
});
Javascript
$("#myBtn").click(function () {
var dataSet= [];
var obj = {
Id: rowIdItem,
Name: rowItem
};
dataSet.push(obj);
var data = {
"RoleId": '1',
"RoleName ": 'roleName',
"RoleList": dataSet
};
$.ajax({
type: "POST",
traditional:true,
url: "controller/VerifyRole",
content: "application/json;",
dataType: "json",
data: data ,
success: function () {
}
});
});
Controller/Action
[HttpPost]
public ActionResult VerifyRole(SaveUserNewRoleViewModel input)
{
...
}
Try this:)
$(document).on("submit", "#modal", function (e) {
e.preventDefault();
var selectedText = $("##Html.IdFor(m=>m.RoleId) :selected").text();
var selectedId = $("##Html.IdFor(m=>m.RoleId)").val();
var form_data = {};
form_data.RoleId = selectedId;
form_data.RoleName =selectedText;
console.log(form_data);
rowIdItem = selectedId;
rowItem = selectedText;
$("#close").trigger("click");
$.ajax({
url: "#Url.Action("VerifyRole", #ViewContext.RouteData.Values["controller"].ToString())",
method: "POST",
data: JSON.stringify(form_data),
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function (result) {
if (result.success) {
rowIdItem = selectedId;
rowItem = selectedText;
$("#close").trigger("click");
return;
}
$.each(result.errors, function (index, item) {
// Get message placeholder
var element = $('[data-valmsg-for="' + item.propertyName + '"]');
element.empty();
// Update message
element.append($('<span></span>').text(item.errorMessage));
// Update class names
element.removeClass('field-validation-valid').addClass('field-validation-error');
$('#' + item.propertyName).removeClass('valid').addClass('input-validation-error');
});
}
});
return false;
});
my example with datasets:
$("body").on("click", "#btnSave", function () {
var ops = new Array();
$("#table TBODY TR").each(function () {
var row = $(this);
var ps = {};
ps.colname1 = row.find("TD").eq(0).html();
ps.colname2 = row.find("TD").eq(1).html();
ps.colname3= row.find("TD").eq(2).html();
ops.push(ps);
});
var item = {};
item.nam1 = "test";
item.List = ops;
$.ajax({
type: "POST",
url: " ...",
data: JSON.stringify(item),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
}
});
});

Delete record by using ajax from database EntityFramework

I am beginner and trying to delete the record from database by using JavaScript, Ajax and Json in MVC Entity Framework. But my delete button is not working well.
In controller class my action code is
public ActionResult Delete(int id) {
using (StudentContext db = new StudentContext()) {
Student std = db.Student.Where(x => x.Id == id).FirstOrDefault<Student>();
db.Student.Remove(std);
db.SaveChanges();
}
return Json(true, JsonRequestBehavior.AllowGet);
}
and my JavaScript code is
<button id='deleteRecord'>delete</button>
$("#deleteRecord").click(function () {
var StudentId = $(this).val();
var stdId = parseInt(StudentId);
$.ajax({
url: "/AjaxStudent/Delete",
type: 'Delete',
data: {
StudentId: stdId
}
}).done(function () {
alert("Deleted")
});
});
}).error(function () {
alert("Failed")
});
I shall be very thankful if anybody help me.
You need to add your model id in jquery data tag:
<button id='deleteRecord' data-model-id="#model.Id">delete</button>
Then in javascript code:
$("#deleteRecord").click(function () {
var StudentId = $(this).data("model-id");
var url = "/AjaxStudent/Delete/" + StudentId;
$.ajax({
url: url,
type: 'Delete',
}).done(function () {
alert("Deleted")
});
});
}).error(function () {
alert("Failed")
});
I think that the error comes from the type attribute of your ajax call. You assign "delete" to this attribute, but it must be "POST":
$.ajax({
url: "#Url.Action("Delete","AjaxStudent")",
type: "POST", // here is your problem,
data: { StudentId: stdId },
dataType: 'json',
success: function() {
alert("Deleted");
},
error: function(dat) {
alert(data.x);
}
});
And the action method in your controller must be decorated with [httppost] :
[HttpPost]
public JsonResult Delete(int StudentId)
{
using (StudentContext db = new StudentContext())
{
Student std = db.Student.Where(x => x.Id == StudentId).FirstOrDefault<Student>();
db.Student.Remove(std);
db.SaveChanges();
}
return Json(true, JsonRequestBehavior.AllowGet);
}
you should try by changing :
$.ajax({
url: "/AjaxStudent/Delete",
type: 'Delete',
data: {
StudentId: stdId
}
to:
$.ajax({
url: "/AjaxStudent/Delete",
type: 'Delete',
data: {
'id':stdId
}
After lots of time I am able to resolve my problem.
Now my javaScript code
<button class='deleteRecord' data-stid=" + students[i].Id + " >delete</button>
$(".deleteRecord").click(function () {
var StudentId1 = $(this).data("stid");
debugger;
$.ajax({
url: "/AjaxStudent/Delete/" + StudentId1,
type: "Post"
}).done(function () {
getAllStudents();
});
});
});
Controller.cs
public ActionResult Delete(int id) {
using (StudentContext db = new StudentContext()) {
Student std = db.Student.Where(x => x.Id == id).FirstOrDefault();
db.Student.Remove(std);
db.SaveChanges();
}
return Json(true, JsonRequestBehavior.AllowGet);
}

MVC Controller JsonResult error Server cannot set content type after HTTP headers have been sent, while return

Have this function in a Controller:
public async Task<JsonResult> getTipoPerfil(int id)
{
PerfilesCalificacion pc = await db.PerfilesCalificaciones.FindAsync(id);
int ret = -1;
if (pc!=null)
{
switch (pc.Tipo)
{
case TipoCalificacion.NotaGlobal:
ret = 0;
break;
case TipoCalificacion.PerfilCalificacion:
ret = 1;
break;
default:
ret = -1; ;
break;
}
}
return new JsonResult { Data = ret };
}
In the return line above I'm getting the error.
I searched a lot but I cannot find the solution.
This function it is called by a JS function. This is part of the HTML (cshtml):
.
.
.
#Html.DropDownListFor(model => model.ApiTdEx.PerfilCalificacionId, (List<SelectListItem>)ViewBag.LstPerfiles, new { #class = "form-control", #onchange = "MuestraPerfil()" })
.
.
.
<script>
function MuestraPerfil() {
var idperfil = document.getElementById("ApiTdEx_PerfilCalificacionId").value;
$.ajax({
type: 'POST',
url: '#Url.Action("getTipoPerfil", "MenuProfesor")',
dataType: 'json',
data: { id: $("#ApiTdEx_PerfilCalificacionId").val() },
success: function (tipo) {
alert(tipo);
},
error: function (request, status, error) {
alert(error);
}
});
}
</script>
I have some code in global.asax that maybe have some relation:
private void Application_BeginRequest(Object source, EventArgs e)
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
context.Response.BufferOutput = true;
string culture = null;
if (context.Request.UserLanguages != null && Request.UserLanguages.Length > 0)
{
culture = Request.UserLanguages[0];
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(culture);
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
}
}
Thanks a lot!

Getting Null object array jquery post

I am new to Angular.js framework. I am getting data which i am further assigning to array using angular scope.
Modal.CS:
public class AppSetting1
{
public int lng_AppSettings { get; set; }
public string str_SettingName { get; set; }
public string str_SettingValue { get; set; }
public string str_Type { get; set; }
public AppSetting1(int _lng_AppSettings, string _str_SettingName, string _str_SettingValue, string _str_Type)
{
lng_AppSettings = _lng_AppSettings;
str_SettingName = _str_SettingName;
str_SettingValue = _str_SettingValue;
str_Type = _str_Type;
}
}
internal string GetAppSettings()
{
try
{
List<AppSetting1> objAppsettings = new List<AppSetting1>();
objAppsettings.Add(new AppSetting1(1,"Name1","Value1","Type"));
objAppsettings.Add(new AppSetting1(2, "Name2", "Value2", "Type2"));
return JsonConvert.SerializeObject(objAppsettings, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
}
catch (Exception ex)
{
throw ex;
}
}
Controller.CS:
[AuthCheckService, SessionCheckService]
[HandleModelStateException]
public string GetAppSettings()
{
try
{
ManageAppSettings accExec = new ManageAppSettings();
return accExec.GetAppSettings();
}
catch (Exception ex)
{
throw new ModelStateException(ex.Message, ex.InnerException);
}
}
[HttpPost]
public JsonResult SaveSettings(List<AppSetting1> AppSetting)
{
try
{
ManageAppSettings accExec = new ManageAppSettings();
return Json(AppSetting, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
throw new ModelStateException(ex.Message, ex.InnerException);
}
}
Angular.js:
(function () {
var app = angular.module('myAppSeetings', []);
app.controller('AppSettingsController', function ($scope) {
$scope.items = [];
$scope.SaveSettings = function () {
if (validate()) {
var token = $('[name=__RequestVerificationToken]').val();
var test = $scope.items;
$.ajax({
beforesend: showProgress(),
type: 'POST',
headers: { "__RequestVerificationToken": token },
url: getAppPath() + 'AppSettings/SaveSettings',
dataType: 'json',
data: { AppSetting: $scope.items },
success: function (result) {
if (result != "") {
//ShowSaveMessage(result);
//fetchData();
//$('#EditPopUp').css('display', 'none');
//$('#exposeMaskManageUser').css('display', 'none');
//clearForm();
}
else
ShowErrorPopup('An error has occurred. Please contact System Administrator.');
},
complete: hideProgress,
error: function (ex) {
ShowErrorPopup('An error has occurred. Please contact System Administrator.');
}
});
}
else {
ShowWarningMessage('Required fields must be completed prior to completing the work');
}
};
function fetchData() {
var token = $('[name=__RequestVerificationToken]').val();
$.ajax({
beforesend: showProgress(),
type: 'GET',
headers: { "__RequestVerificationToken": token },
url: getAppPath() + 'AppSettings/GetAppSettings',
dataType: 'json',
success: function (data) {
// console.log(data);
$scope.items = data;
$scope.$apply();
console.log($scope.items);
},
complete: hideProgress,
error: function (ex) {
ShowErrorPopup('An error has occurred. Please contact System Administrator.');
}
});
};
function validate() {
var val = true;
if ($("input").val().trim() == "") {
val = false;
}
return val;
}
fetchData();
});
})();
Problem:
On save click i am getting null on server side. Where i am going wrong here?
Try adding
contentType: 'application/json; charset=utf-8',
See this answer
Your code wrong here:
data: { AppSetting: $scope.items }
It should be
data: $scope.items
In your saveClick function: $scope.items now is []. It should have some values as you expect. Depend on your case it is from client or a default value for testing:
$scope.items = [{lng_AppSettings: 1, str_SettingName : 'Name 1'},
{lng_AppSettings: 2, str_SettingName : 'Name 2'}];

How can post multiple arrays using JSON.stringify()?

I am trying to post multiple arrays to my controller using Ajax post. First I have a model like this:
public class EnrollmentOptionsVM
{
public virtual string OptionID{ set;get;}
public virtual string UserChoice { set;get;}
public virtual string TchOptionID { set; get; }
public virtual string TeacherChoice { set; get; }
}
Then my script:
<script type="text/javascript">
var $checkboxes = $('input[type="checkbox"]');
var $strInstructors = $('input[name="instructorString"]');
$(document).ready(function () {
$('#saveBtn').click(function () {
var teacherOptions = [];
var options = [];
$.each($checkboxes, function () {
if ($(this).is(':checked')) {
var item = { "UserChoice": "checked", "OptionID": "YouCanSetIDHere" };
}
else {
var item = { "UserChoice": "unchecked", "OptionID": "YouCanSetIDHere" };
}
options.push(item);
})
$.each($strInstructors, function () {
if ($(this).is(':selected')) {
var tchItem = { "TeacherChoice": "checked", "TchOptionID": "SetTchIDHere" };
}
else {
var tchItem = { "TeacherChoice": "unchecked", "TchOptionID": "SetTchIDHere" };
}
options.push(tchItem);
})
$.ajax({ type:
'POST', url: '#Url.Action("EnrollmentRefresh", "Student")',
contentType: 'application/json',
data: JSON.stringify({firstArray:options, secondArray:teacherOptions})
}).done(function (html) {
});
});
});
</script>
And in my controller here’s the action signature:
[HttpPost]
public ActionResult EnrollmentRefresh(List<EnrollmentOptionsVM> checkedOptions)
{}
When I send only options like this: data: JSON.stringify(options)… it works but when I try to send multiple arrays like the code above it returns null in the controller. How can post multiple arrays using JSON.stringify()?
UPDATE 1
<script type="text/javascript">
var $checkboxes = $('input[type="checkbox"]');
var $strInstructors = $('input[name="instructorString"]');
$(document).ready(function () {
$('#saveBtn').click(function () {
var teacherOptions = [];
var options = [];
$.each($checkboxes, function () {
if ($(this).is(':checked')) {
var item = { "UserChoice": "checked", "OptionID": "YouCanSetIDHere" };
}
else {
var item = { "UserChoice": "unchecked", "OptionID": "YouCanSetIDHere" };
}
options.push(item);
})
$.each($strInstructors, function () {
if ($(this).is(':selected')) {
var tchItem = { "TeacherChoice": "checked", "TchOptionID": "SetTchIDHere" };
}
else {
var tchItem = { "TeacherChoice": "unchecked", "TchOptionID": "SetTchIDHere" };
}
teacherOptions.push(tchItem);
})
$.ajax({ type:
'POST', url: '#Url.Action("EnrollmentRefresh", "Student")',
contentType: 'application/json',
data: JSON.stringify({checkedOptions:options,selectedTeacher:teacherOptions})
}).done(function (html) {
});
});
});
</script>
And in the controller:
[HttpPost]
public ActionResult EnrollmentRefresh( List<EnrollmentOptionsVM> checkedOptions, List<TeacherOptionMV> selectedTeachers)
{}
Two ViewModels
public class TeacherOptionMV
{
public virtual string TchOptionID { set; get; }
public virtual string TeacherChoice { set; get; }
}
And
public class EnrollmentOptionsVM
{
public virtual string OptionID{ set;get;}
public virtual string UserChoice { set;get;}
}
You are not posting multiple arrays with {firstArray:options, secondArray:teacherOptions}. You are posting a single object with two properties: firstArray and secondArray. Your controller is designed to get only one array of EnrollmentOptionsVM. The best thing to do, I guess, is to change EnrollmentRefresh method to take some object with fields firstArray and secondArray (or something like that) as an argument.

Categories

Resources