So I am trying to set up ko validation for my partial view. I pretty much implemented the same deisgn as another partial view that has the ko validation. It works perfectly there, but with this partial view it doesn't work.
This is what I have in javascript:
ko.validation.configure({
insertMessages: false,
decorateElement: true,
errorElementClass: 'error'
});
function Reference(referenceId, id, firstName, lastName, title, email, company, phone) {
this.ReferenceId = ko.observable(referenceId);
this.Id = id;
this.FirstName = firstName;
this.LastName = lastName;
this.Title = title;
this.Company = company;
this.Email = email;
this.Phone = phone;
}
var viewModel = function () {
var self = this;
self.FirstName = ko.observable().extend({ required: true });
self.LastName = ko.observable().extend({ required: true });
self.Title = ko.observable();
self.Email = ko.observable().extend({ required: true, email: true });
self.Phone = ko.observable().extend({ required: true });
self.Company = ko.observable().extend({ required: true });
addReferenceValidationGroup = ko.validatedObservable({
FirstName: self.FirstName,
LastName: self.LastName,
Phone: self.Phone,
Email: self.Email,
Company: self.Company
});
self.addReference = function () {
if (!addReferenceValidationGroup.isValid()) {
console.log(addReferenceValidationGroup.errors());
addReferenceValidationGroup.errors.showAllMessages();
return false;
} else {
var newReference = new Reference(0, this.CandidateId(), self.FirstName(), self.LastName(), self.Title(), self.Email(), self.Company(), self.Phone());
console.log(newReference);
$.ajax({
url: '#Url.Action("AddReference")',
type: "POST",
data: ko.toJSON(newReference),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
newReference.ReferenceId(result.message); //Sets the InterviewId to the new one
},
error: function (result) {
}
});
this.References.push(newReference);
self.FirstName('');
self.LastName('');
self.Title('');
self.Email('');
self.Phone('');
self.Company('');
self.FirstName.isModified(false);
self.LastName.isModified(false);
self.Email.isModified(false);
self.Phone.isModified(false);
self.Company.isModified(false);
}
};
self.goNext = function () {
$.ajax({
url: '#Url.Action("JobDepartures")',
type: "POST",
data: ko.toJSON(this),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
ko.removeNode(document.getElementById("referencesDiv"));
$("#dynamicData").html(result.message);
}
});
};
};
var jsonModel = '#Html.Raw(JsonConvert.SerializeObject(this.Model))';
var mvcModel = ko.mapping.fromJSON(jsonModel);
var myViewModel = new viewModel();
var g = ko.mapping.fromJS(myViewModel, mvcModel);
ko.applyBindings(g, document.getElementById("referencesDiv"));
This is what I have in the HTML:
<input data-bind="value: FirstName, validationElement: FirstName" class="input" type="text" />
<input data-bind="value: LastName, validationElement: LastName" class="input" type="text" />
Etc.
NOTE: This is line of code that always returns FALSE.
addReferenceValidationGroup.isValid()
Also this line doesn't add 'error' class to any of the controls. So it doesn't get highligted red either:
addReferenceValidationGroup.errors.showAllMessages();
PLEASE PLEASE HELP!
EDIT: Here is the Model properties:
public int CandidateId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Title { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Company { get; set; }
public List<ReferenceViewModel> References
{
get;
set;
}
I think the problem is with this statements:
var jsonModel = '#Html.Raw(JsonConvert.SerializeObject(this.Model))';
var mvcModel = ko.mapping.fromJSON(jsonModel);
var myViewModel = new viewModel();
var g = ko.mapping.fromJS(myViewModel, mvcModel);
ko.applyBindings(g, document.getElementById("referencesDiv"));
VS.
var viewModel = #Html.Raw(Json.Encode(Model));
ko.applyBindings(viewModel, document.getElementById("referencesDiv"));
Somewhere along with JsonConvert.SerializeObject and trying to mapping two viewmodels together.
Related
public Class MainModel
{
public IFormFile PDF { get; set; }
public List<TempModel> List1{ get; set; }
public List<TempModel1> List2 { get; set; }
}
public class TempModel
{
public string Prop1{ get; set; }
public string Prop2{ get; set; }
}
public class TempModel1
{
public string Prop1{ get; set; }
public string Prop2{ get; set; }
public List<TempModel> list1 { get; set; }
}
function AJAXCall()
{
var list1 = [{Prop1: "abcd",Prop2: "abcd1"},{Prop1: "abcd123",Prop2: "abcd456"}]
var list2 = [{Prop1: "abcd",Prop2: "abcd1",list1:list1 },{Prop1: "abcd123",Prop2: "abcd456",list1:list1}]
formData.append("PDF", files[i]);
formData.append("List1", list1);
formData.append("List2", list2);
$.ajax({
type: "POST",
url: url,
data: formData,
processData: false,
contentType: false,
success: function (data) {
}
});
}
public IActionResult Save([FromBody] MainModel model, IFormFile PDF)
{
}
I tried almost everything. Can you please help to get these details to be sent to the server-side?
In Controller, I am not getting any values from AJAX Call.
URL is correct, it is hitting the Controller Action Method but values are returning null.
What is the correct way to accomplish this task as I Have tried many things but it did not work out.
Here is a demo:
View:
<input type="file" id="images" multiple />
<button onclick="AJAXCall()">ajax</button>
#section scripts{
<script>
function AJAXCall() {
var formData = new FormData();
var files = $("#images").get(0).files;
formData.append('PDF', files[0]);
var list1 = [{ Prop1: "abcd", Prop2: "abcd1" }, { Prop1: "abcd123", Prop2: "abcd456" }]
var list2 = [{ Prop1: "abcd", Prop2: "abcd1", list1: list1 }, { Prop1: "abcd123", Prop2: "abcd456", list1: list1 }]
for (var i = 0; i < list1.length; i++) {
formData.append("List1[" + i + "].Prop1", list1[i].Prop1);
formData.append("List1[" + i + "].Prop2", list1[i].Prop2);
}
for (var i = 0; i < list2.length; i++) {
formData.append("List2[" + i + "].Prop1", list2[i].Prop1);
formData.append("List2[" + i + "].Prop2", list2[i].Prop2);
for (var j = 0; j < list1.length; j++) {
formData.append("List2[" + i + "].list1[" + j + "].Prop1", list1[j].Prop1);
formData.append("List2[" + i + "].list1[" + j + "].Prop2", list1[j].Prop2);
}
}
$.ajax({
type: "POST",
url: "Save",
data: formData,
processData: false,
contentType: false,
success: function (data) {
}
});
}
</script>
}
Controller:
public IActionResult Save(MainModel model)
{
return Ok();
}
result:
my model:
public class Hello
{
public List<string> name;
public List<string> phone;
public List<string> contact;
}
my controller code is
public ActionResult Home(Hello obj) // obj is coming out to be null
{
}
my script is
var names =[];
var phones =[];
var contacts = [];
// some code to fill the arrays
var obj = [{
name: names,
phone: phones,
contact: contacts,
}];
debugger;
$.ajax({
cache: false,
url: 'Home',
data: { obj:obj },
success: function (data) {
var response = JSON.parse(data);
window.location = 'Download?fileGuid=' + response.FileGuid
+ '&filename=' + response.FileName;
}
})
i can see in the debugger that data is stored in the arrays but when i am sending data to controller the obj is null can someone suggests where am i going wrong ?
You have object in code behind so do not pass array of Hello object.
And also use POST request because GET request have not message body.
Please use below
var obj = {
name: ['1', '2', '3'],
phone: ['234324', '34343243', '3434234234'],
contact: ['Test1', 'Test2', 'Test3']
};
debugger;
$.ajax({
type:'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
url: 'Home',
data:JSON.stringify({ obj: obj }),
success: function (data) {
var response = JSON.parse(data);
// window.location = 'Download?fileGuid=' + response.FileGuid
+ '&filename=' + response.FileName;
}
})
public class Hello
{
public List<string> name { get; set; }
public List<string> phone { get; set; }
public List<string> contact { get; set; }
}
Actually i solved the problem , i had to set
traditional:true,
in my ajax call
Hi below is my question.
How to send Javascript array object to the MVC5 controller method.
The code successfully hit the action method but the list value param value is null. I tried different combination with the JSON.stringify as well.
//object class
public class MassPayoutItem
{
public string ReciverEmailID { get; set; }
public string Amount { get; set; }
public int ProviderID { get; set;}
public string AppintmentsID { get; set; }
public string TransictionID{get;set;}
public string TransictionStatus { get; set; }
public string ProviderName { get; set;}
}
//Action method
public ActionResult GetProviderMassPaymentDetail(List<MassPayoutItem> PayoutItemList){
return Json(new { Result = true, ResultData = ResaultData, Message = "" }, JsonRequestBehavior.AllowGet);
}
//JavaScript Code
function MassPay() {
alert("called MassPay");
var MassPymentList = new Array();
var objs;
$('.Include_Payment:checked').each(function () {
var ReciverEmailId = $(this).parents('tr').attr("emailid");
var appointmentids = $(this).parents('tr').attr("appointmentids");
var ProviderID = $(this).parents('tr').attr("UserId");
var Amount = $(this).parents('tr').find(".Amount").text();
var ProviderName = $(this).parents('tr').find(".OwnerName").text();
MassPymentList.push({ "ReciverEmailID": ReciverEmailId, "Amount": Amount, "ProviderID": ProviderID, "AppintmentsID": appointmentids, "ProviderName": ProviderName, "TransictionID": "abc", "TransictionStatus": "bcd" });
});
objs = JSON.stringify({ "PayoutItemList": MassPymentList });
debugger;
// _PageUrl.PayMassTransiction
// '#Url.Action("GetProviderMassPaymentDetail","Controller")'
//The call hits the method but the value is null
$.ajax({
Type: "POST"
, url: _PageUrl.PayMassTransiction
, contentType: "application/json,charset=utf-8",
traditional: true
, data: objs,
datatype: "json",
success: function (result) {
debugger;
alert("called");
}
, error: function (result) {
}
});
}
Hi Finally I solve the issue.
public class MassPayoutItem
{
public string ReciverEmailID { get; set; }
public string Amount { get; set; }
public int ProviderID { get; set;}
public string AppintmentsID { get; set; }
public string TransictionID{get;set;}
public string TransictionStatus { get; set; }
public string ProviderName { get; set;}
}
//Action method
**//This is first change i have make.**
[HttpPost, ActionName("GetProviderMassPaymentDetail")]
public ActionResult GetProviderMassPaymentDetail(List<MassPayoutItem> PayoutItemList){
return Json(new { Result = true, ResultData = ResaultData, Message = "" }, JsonRequestBehavior.AllowGet);
}
//JavaScript Code
function MassPay() {
alert("called MassPay");
var MassPymentList = new Array();
var objs;
$('.Include_Payment:checked').each(function () {
var ReciverEmailId = $(this).parents('tr').attr("emailid");
var appointmentids = $(this).parents('tr').attr("appointmentids");
var ProviderID = $(this).parents('tr').attr("UserId");
var Amount = $(this).parents('tr').find(".Amount").text();
var ProviderName = $(this).parents('tr').find(".OwnerName").text();
MassPymentList.push({ "ReciverEmailID": ReciverEmailId, "Amount": Amount, "ProviderID": ProviderID, "AppintmentsID": appointmentids, "ProviderName": ProviderName, "TransictionID": "abc", "TransictionStatus": "bcd" });
});
objs = JSON.stringify({PayoutItemList: MassPymentList });
debugger;
// _PageUrl.PayMassTransiction
// '#Url.Action("GetProviderMassPaymentDetail","Controller")'
//The call hits the method but the value is null
// below is the changed ajax calll change Type to type
$.ajax({
type: "POST"
, url: _PageUrl.PayMassTransiction
, contentType: "application/json,charset=utf-8"
,async: false
,traditional: true
, data: objs,
datatype: "json",
success: function (result) {
debugger;
alert("called");
}
, error: function (result) {
}
});
}
I'm trying to post an array of values back to my action method, but with no luck as I'm getting a null for 'ParcelList'. Upload Files argument is being populated, just having a problem with ParcelList.
//ParcelList returning null
public ActionResult Add(AddShipmentVM model, ParcelVM[] ParcelList, HttpPostedFileBase[] UploadFiles )
{
if (ModelState.IsValid)
{
return RedirectToAction("Home", "CustomClearence");
}
return View(model);
}
ParcelVM
public class ParcelVM
{
[Required(ErrorMessageResourceType = typeof(AddShipmentVM), ErrorMessageResourceName = "RequiredValue")]
public string TrackTrace { get; set; }
[Required(ErrorMessageResourceType = typeof(AddShipmentVM), ErrorMessageResourceName = "RequiredValue")]
[RegularExpression(#"^\d{0,3}\.?(\d{3,3})*,?\d{1,2}$", ErrorMessageResourceType = typeof(AddShipmentVM), ErrorMessageResourceName = "InvalidWeight")]
public string GrossWeight { get; set; }
public decimal Parcelno { get; set; }
}
Ajax
When user clicks on finish, submit form
$(".actions a[href=#finish]").click(function () {
var form = jQuery('#addShipmentForm').serializeObject();
var parcelList = $.parseJSON(ko.toJSON(viewModel.parcelList()));
var tariffList = $.parseJSON(ko.toJSON(viewModel.tariffList()));
var dashBoardurl = '#Url.Action("Home","Shipment")'
var tariffObject = JSON.stringify({ TariffList: tariffList });
$('#uploadDocument input[type=file]')[0].files }
var UploadFiles = { UploadFiles: $('#uploadDocument input[type=file]')[0].files }
$.extend(form, { FinancialAndCustomsModel: tariffObject });
$.extend(form, { ParcelList: parcelList });
$.extend(form, UploadFiles);
$.ajax({
type: "POST",
data: form,
contentType: false,
success: function (result) {
if (result.status == "success") {
$(location).attr('href', dashBoardurl);
}
else {
//$(location).attr('href', addRequestUrl);
}
},
cache: false,
processData: false
});
});
i am using ASP.NET MVC5 and intended to read json data from controller to view in razor page using kendo grid. I am using trial version for time being so i don't have access to kendo server scripting and helper classes... i have jsonResult in controller and i want ajax to call this function from view--> javascript to read and print data...
model class
[Table("FeeZone")]
public class FeeZone
{
public FeeZone()
{
}
[Key]
public int FeeZoneID { get; set; }
[Required]
public string FeeZoneDescription { get; set; }
[StringLength(50, ErrorMessage = "Description Max Length is 50")]
[Required]
public string CurrencyLabel { get; set; }
[StringLength(10, ErrorMessage = "Description Max Length is 10")]
[Required]
public string CurrencySymbol { get; set; }
[StringLength(50, ErrorMessage = "Description Max Length is 50")]
[Required]
public string CurrencyCode { get; set; }
}
Controller class
public ActionResult FreeZone()
{
var query_result = Q_UOF.GetAllFeeZone();
return View(query_result.ToList());
}
public JsonResult GetAllFreeZone()
{
var allFreeZone = Q_UOF.GetAllFeeZone().ToList();
return Json(allFreeZone, JsonRequestBehavior.AllowGet);
}
razor -- view page
model IEnumerable<DatabaseLayer.TableMappings.FeeZone>
#{
ViewBag.Title = "FreeZone";
Layout = "~/Views/Shared/_Layout_Master.cshtml";
}
<script type="text/javascript">
$(document).ready(function () {
//load ALl freeZone from JSON Method
var RemoteJsonData = new kendo.data.DataSource(
{
transport:
{
read: {
type: "Get",
dataType: "json",
url: "Qualification/GetAllFreeZone"
},
pageSize: 4
}
})
//View all FreeZone data in Kendo Grid
$("#FreeZone_ViewAll_Grid").kendoGrid({
columns: [
{ title: "FeeZoneID" },
{ title: "FeeZoneDescription" },
{ title: "CurrencyLabel" },
{ title: "CurrencySymbol" },
{ title: "CurrencyCode" }
],
dataSource: RemoteJsonData
});
})
</script>
<div id="FreeZone_ViewAll_Grid"></div>
$.ajax({
url: '#Url.Action("GetAllFreeZone", "Qualification")',
type: 'POST',
dataType: "json",
success: function (result) {
var Freezone=result.Freezone;
var dataSource = new kendo.data.DataSource({
data:Freezone
});
$('#FreeZone_ViewAll_Grid').data('kendoGrid').dataSource.data(Freezone);
},
async: false
});
Controller function
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult GetAllFreeZone([DataSourceRequest] DataSourceRequest request)
{
var allFreeZone = Q_UOF.GetAllFeeZone().ToList();
return Json(allFreeZone.ToDataSourceResult(request));
}