Model is not updating while submitting form AJAX Asp.Net MVC - ajax

I have got a MVCapplication where I am collecting details on form having KENDO controls, and along side I can update couple of dropdown controls using AJAX.
The problem I am facing currently that, when I submit the form with changed values in dropdown, and other controls doesn't updates the model, and it remains the same, even if the form shows the updated values, the model retains the old values.
I have tried all sorts of solutions and googled enough but no success. I am putting my code below to show what I am doing at the moment, anyone there, could look at it and guide me as what am I doing wrong.
VIEW
#(Html.Kendo().DropDownList()
.Name("ddlDateRange")
.DataTextField("Name")
.DataValueField("Id")
.BindTo(Model.ReportIntervals)
.Events(e =>
{
e.Change((#<text>
function()
{
var selectedDateRange = $("#ddlDateRange").data("kendoDropDownList").value();
$.ajax({
url: '#Url.Action("ChangeStartEndDates")',
type: 'POST',
data: JSON.stringify({ selectedDateRange: selectedDateRange }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data) {
$("#StartDate").data("kendoDatePicker").value(data.StartGamingDate);
$("#EndDate").data("kendoDatePicker").value(data.EndGamingDate);
},
error: function () { alert('Error in DateRange dropdownlist'); }
});
}
</text>));
})
)
#(Html.Kendo().DatePickerFor(model => model.StartGamingDate)
.Name("StartDate")
.Events(e =>
{
e.Change((#<text>
function()
{
var startDate = $("#StartDate").val();
var endDate = $("#EndDate").val();
$.ajax({
url: '#Url.Action("ChangeDateRangeName")',
type: 'POST',
data: JSON.stringify({ startDate: startDate, endDate: endDate }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data) {
$("#ddlDateRange").data("kendoDropDownList").text(data.ReportInterval.Name);
},
error: function () { alert('Error in StartDate DatePicker'); }
});
}
</text>));
}))
#(Html.Kendo().DatePickerFor(model => model.EndGamingDate)
.Name("EndDate")
.Events(e =>
{
e.Change((#<text>
function()
{
var startDate = $("#StartDate").val();
var endDate = $("#EndDate").val();
$.ajax({
url: '#Url.Action("ChangeDateRangeName")',
type: 'POST',
data: JSON.stringify({ startDate: startDate, endDate: endDate }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data) {
$("#ddlDateRange").data("kendoDropDownList").text(data.ReportInterval.Name);
},
error: function () { alert('Error in EndDate DatePicker'); }
});
}
</text>));
}))
CONTROLLER
**MODEL VALUES FORTHIS ACTION**
systemAuditReportViewModel.StartGamingDate = "01/01/2013";
systemAuditReportViewModel.EndGamingDate = "31/12/2013";
systemAuditReportViewModel.ReportInterval.Id = 30;
systemAuditReportViewModel.ReportInterval.Name = "Last Calender Year";
[HttpPost]
public JsonResult ChangeStartEndDates(int selectedDateRange)
{
SystemAuditReport systemAuditReportViewModel = new SystemAuditReport();
Nullable<DateTime> startGamingDate;
Nullable<DateTime> endGamingDate;
IG.General.Web.Model.ReportInterval reportInterval = new IG.General.Web.Model.ReportInterval();
reportInterval.Id = selectedDateRange;
IG.General.Web.Model.ReportIntervalFactory.GetDateRange(reportInterval, out startGamingDate, out endGamingDate);
systemAuditReportViewModel.StartGamingDate = startGamingDate;
systemAuditReportViewModel.EndGamingDate = endGamingDate;
return Json(systemAuditReportViewModel, JsonRequestBehavior.AllowGet);
}
**MODEL VALUES FOR THIS ACTION**
systemAuditReportViewModel.StartGamingDate = "27/03/2014";
systemAuditReportViewModel.EndGamingDate = "27/03/2014";
systemAuditReportViewModel.ReportInterval.Id = 2;
systemAuditReportViewModel.ReportInterval.Name = "Today";
[HttpPost]
public ActionResult GenerateReport(SystemAuditReport systemAuditReportViewModel)
{
var errors = ModelState.Values.SelectMany(v => v.Errors);
ReportContainer reportContainer = new ReportContainer();
if (ModelState.IsValid)
{
systemAuditReportViewModel.ReportPath = "/reports/";
//systemAuditReportViewModel.StartGamingDate = startDate;
//systemAuditReportViewModel.EndGamingDate = endDate;
this.CreateReport(systemAuditReportViewModel, out reportContainer);
}
return View(reportContainer);
}

We had struggled with this a bit as well. The binding is a little tricky with templates. You have to name the DropDownList the same as the model's bound index.
#model string
#(Html.Kendo().DropDownListFor(m => m)
.BindTo("#=Model.EntityClassId")
.DataTextField("Value")
.DataValueField("Id")
.Name("EntityClassId")
.OptionLabel(MyApp.Resources.Text.DamageTypeOptionLabel)
.AutoBind(true)
.DataSource( source => source
.Read( read=>read.Action("SomeMethod", "SomeController"))
.ServerFiltering(true)
)
.Events(events => events
.Select("onDamageTypeSelected")
.Change("onDamageTypeChanged")
.DataBound("onDamageTypeDatabound")
)
.HtmlAttributes(new{style="height:21px;vertical-align:center"})
)

Related

Ajax post zero to controller

I'm trying to POST an int with Ajax to my controller
Js
<script>
function FillCity() {
var provinceId = $(provinces).val();
$.ajax({
url: "FillCity",
type: "POST",
data: { id: provinceId },
dataType: "json",
traditional: true,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#cities").html(""); // clear before appending new list
$.each(data, function (i, city) {
$("#cities").append(
$('<option></option>').val(city.Id).html(city.Name));
});
}
});
}
</script>
code in my controller :
[HttpPost]
public ActionResult FillCity(int id)
{
var cities = _context.City.Where(c => c.ProvinceId == 5);
return Json(cities);
}
but it always post 0 as id, I tried digits instead of provinceId, but it rtills send 0
You should create an class that have a Id Property.
public class ProvinceIdDto
{
public int Id { get; set; }
}
replace int id with ProvinceIdDto model in action
[HttpPost]
public ActionResult FillCity(ProvinceIdDto model)
{
var cities = _context.City.Where(c => c.ProvinceId == model.Id);
return Json(cities);
}
replace { id: provinceId } with JSON.stringify({ Id: provinceId }),
<script>
function FillCity() {
var provinceId = $(provinces).val();
$.ajax({
url: "FillCity",
type: "POST",
data: JSON.stringify({ Id: provinceId }),
dataType: "json",
traditional: true,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#cities").html(""); // clear before appending new list
$.each(data, function (i, city) {
$("#cities").append(
$('<option></option>').val(city.Id).html(city.Name));
});
}
});
}
</script>
Another options is you can replace HttpPost method with HttpGet and pass id to action like this.
Change type: "POST", to type: "GET",
<script>
function FillCity() {
var provinceId = $(provinces).val();
$.ajax({
url: "FillCity?id="+provinceId,//<-- NOTE THIS
type: "GET",//<-- NOTE THIS
dataType: "json",
traditional: true,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#cities").html(""); // clear before appending new list
$.each(data, function (i, city) {
$("#cities").append(
$('<option></option>').val(city.Id).html(city.Name));
});
}
});
}
</script>
C#
[HttpGet]
public ActionResult FillCity(int id)
{
var cities = _context.City.Where(c => c.ProvinceId == id);
return Json(cities);
}
when you do { id: provinceId } you are creating an object with property id
in your controller you are just expecting an id. You will need to ether:
A pass it as a query parameter url: "FillCity?id=" + provinceId
B create an object to be parsed from the request body.
public class Payload {
public int Id {get;set;}
}
and use it like this
public ActionResult FillCity([FromBody] Payload payload)
Can you verify this statement has a value:
var provinceId = $(provinces).val();
It's possible that isn't finding what you are looking for, and because you have the type int as a parameter, it defaults it to "0".
You shouldn't need to change it to a GET and your MVC method is fine as is. You can see from JQuery's own sample it should work:
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
I think it might not be finding the input field successfully.

Returning error from controller to AJAX jQuery

I works with ASP.net MVC and I have get "Error" from belowe my JavaScript code:
This is my AJAX jQuery code:
$(document).ready(function () {
var dataId;
$(".item2 .small-img").click(function () {
dataId = $(this).data("id");
var url = '#Url.Action("DecorationTest", "Carpet")' + "?Id=" + dataId + "&title=" + '#Url.ToFriendlyUrl(Model.Title.ToString())';
$('#dateLink').prop('href', url);
$.ajax({
url: '/Carpet/CheckCarpet',
type: 'POST',
dataType: 'Json',
data: '{"CarpetImageid":"' + dataId + '"}',
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.Success == false)
$('#dateLink').hide();
else
$('#dateLink').show();
alert("Success");
},
error: function (errorThrown) {
alert("Error");
}
});
and this is a controller code:
[HttpPost]
public ActionResult CheckCarpet(int CarpetImageid)
{
bool DecorShow = false;
DecorShow = db.Images.Where(x => x.Id == CarpetImageid).FirstOrDefault().DecorTest;
return Json(new JsonData { Success= DecorShow });
}
what's the reason? Someone knows?
I found the solution.i change url to #Url.Action("CheckCarpet", "Carpet") and fixed.
$(".small-img").click(function () {
dataId = $(this).data("id");
var url = '#Url.Action("DecorationTest", "Carpet")' + "?Id=" + dataId + "&title=" + '#Url.ToFriendlyUrl(Model.Title.ToString())';
$('#dateLink').attr('href', url);
$.ajax({
url:'#Url.Action("CheckCarpet", "Carpet")',
type: 'Post',
dataType: 'Json',
data: '{"CarpetImageid":"' + dataId + '"}',
contentType: 'application/json; charset=utf-8',
success: function (result) {
if (result.Success == false) {
$('#dateLink').hide();
$('.p2').hide();
}
else {
$('#dateLink').show();
$('.p2').show();
}
},
error: function (error) {
alert(error.d);
}
});
});

Failed to call action method using Ajax

Here's my JS (jQuery and Ajax) code:
$('#submitSignUp').click(function () {
var name = $('#name').val();
var email = $('#email').val();
var password = $('#password').val();
$.ajax({
url: '#Url.Action("SignUp")',
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify({ name: name, email: email, password: password }),
success: function () {
alert("Rgistered.");
}
})
})
and this is my action method. (It's in "Home controller"):
[HttpPost]
public JsonResult SignUp(string name, string email, string password)
{
TodoNet.Models.TodonetModel database = new TodoNet.Models.TodonetModel();
TodoNet.Models.User oUser = new TodoNet.Models.User()
{
FirstName = name,
LastName = name,
Email = email,
Password = password,
Salt = password,
IsDeleted = false,
IsOnline = false,
PhoneNumber = "09212131212",
RegisterDate = DateTime.Now,
LastLoginDate = DateTime.Now
};
database.Users.Add(oUser);
database.SaveChanges();
return new JsonResult();
}
but I don't know why it doesn't work. after clicking on the '#signUpSubmit' button, the "alert("Registered.")" will not be shown.
What am I doing wrong??
Note: without using Ajax, (by using ordinary send form data to the action method, everything works properly (It means I know that there's nothing wrong with the back-end code)
If the form submitting normally works, then your ajax should be sending form data not json.
Also, prevent the default action of the button click.
$('#submitSignUp').click(function (e) {
e.preventDefault();
$.ajax({
url: '#Url.Action("SignUp")',
type: "POST",
dataType: "json",
data: $("#the_form_id").serialize(),
success: function () {
alert("Rgistered.");
}
});
});
You can also do this way.
On your submitSignUp submit your parameter as following.
var param =
{
name: $('#name').val(),
email: $('#email').val(),
password: $('#password').val()
};
$.ajax({
url: '#Url.Action("SignUp")',
type: "POST",
dataType: 'json',
data: JSON.stringify(param),
async: false,
cache: false,
traditional: true,
contentType: 'application/json',
success: function (data) {
alert(1)
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert(errorThrown);
return false;
}
});
Change your controller:
[HttpPost]
public ActionResult SignUp(string name, string email, string password)
{
//other implementation
return Json("", JsonRequestBehavior.AllowGet);
}
Hope this helps!
Try this as your ajax method -
$('#buttonID').on("click",function() {
var data=
{
var name = $('#name').val();
var email = $('#email').val();
var password = $('#password').val();
};
$.ajax({
url: '#Url.Action("SignUp","ControllerName")',
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify(data),
success: function () {
alert("success");
}
});
});

Lambda fetching multiple records with contains query returns empty

I have this code:
public JsonResult EkranBilgiListele(List<int> ids)
{
dbReklam db = new dbReklam();
//int[] ids = { 14, 16 }; ids comes like this
db.Configuration.ProxyCreationEnabled = false;
var secilenEkranlar = db.tbl_Ekranlar.Where(ekranlar => ids.Contains(ekranlar.sektorID));
return Json(secilenEkranlar);
}
And an AJAX call:
$.ajax({
type: 'POST',
url: '#Url.Action("EkranBilgiListele")',
dataType: 'json',
data: { ids: arraySecilenEkranlarID },
success: function (data) {
console.log('---->' + data.ekranAd);
},
dataType: "json",
traditional: true
});
However, using breakpoints and results view always returns 'empty' and the console returns 'undefined'
Really sorry I wrote wrong query!
Writing right one.
public JsonResult EkranBilgiListele(List<int> ids)
{
//int[] ids = { 14, 16 }; ids comes like this
db.Configuration.ProxyCreationEnabled = false;
var secilenEkranlar = db.tbl_Ekranlar.Where(ekranlar => ids.Contains(ekranlar.ekranID));
return Json(secilenEkranlar);
}
ajax code, changed a little bit:
$.ajax({
type: 'POST',
url: '#Url.Action("EkranBilgiListele")',
dataType: 'json',
data: { ids: arraySecilenEkranlarID },
success: function (secilenEkranlar) {
$.each(secilenEkranlar, function (i, ekranlar) {
console.log(ekranlar.ekranAd);
});
},
error: function (ex) {
alert('İlçeler Çekilemedi.' + ex);
}
});

How to post various custom data types using Ajax in MVC3?

I have this ViewModel to represent each Category and it's several Sub-Categories in my project:
public class Categories
{
//a simple string for the category name
[Required]
public string Cat_Name { get; set; }
//a list of strings for the sub-categories
public List<string> SubCat_Name { get; set; }
}
I pass this model to the view, and I use it to construct my form like this:
#using (Html.BeginForm("Category", "Admin", FormMethod.Post))
{
#Html.TextBoxFor(m => m.Name, new { #class = "Cat" })
#Html.TextBoxFor(m => m.SubName, new { #class = "Sub" })
#Html.TextBoxFor(m => m.SubName, new { #class = "Sub" })
#Html.TextBoxFor(m => m.SubName, new { #class = "Sub" })
#Html.TextBoxFor(m => m.SubName, new { #class = "Sub" })
<input type="button" value="Create New Category" name="Category" onclick="DoIt()" />
}
And as you see, the javascript function "DoIt()" is called by the click on the input button.
here's the function :
function DoIt() {
var stringArray = new Array();
//I put all of the sub-categories inside an array, to be like a list<string>
$(".Sub").each(function (index, value) {
stringArray[index] = this.value;
});
$.ajax({
url: '/Admin/Category',
type: "POST",
data: JSON.stringify($(".Cat").attr("value") , stringArray),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () { console.log("post done"); },
error: function () { }
});
}
As you can see, in the ajax method I'm trying to pass the "Category Name" $(".Cat").attr("value") and it's "Sub-Category Names" stringArray to the corresponding action method which requires Categories datatype I created as a viewmodel before. It looks like this:
public ActionResult Category(Categories CAT)
{
//Do something
return View();
}
The problem is the ajax method can't post two datatypes at once, or just that I don't know how to do it.
I also tried this :
var postdata = {
Name: $(".Cat").attr("value"),
SubName: stringArray
};
and put postdata inside the JSON.stringify() instead. But still nothing is passed to the action method.
I think you are very close.
Try this
var postdata = {
Cat_Name: $(".Cat").val(),
SubCat_Name: stringArray
};
&
$.ajax({
url: '/Admin/Category',
type: "POST",
data: JSON.stringify(CAT:postdata),
dataType: "json",
contentType: "application/json",
success: function () { console.log("post done"); },
error: function () { }
});
Try to send data formatted like this:
$.ajax({
url: '/Admin/Category',
type: "POST",
data: JSON.stringify({ Cat_Name: $(".Cat").val(), SubCat_Name: stringArray }),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () { console.log("post done"); },
error: function () { }
});

Resources