Javascript array sending to asp.net MVC controller - javascript

I'm currently trying to develop a web app in which a user defines a set of points with coordinates on google maps, these points are stored on an array like this one:
mvcPolygon: new google.maps.MVCArray(),
Now I need username, password, etc. and submits it to the server. I'm pretty new with javascript and frontend development so I'm quite clueless here as to what is the way to go.
So currently I have the javascript code which is storing the coordinates and what I need is that when the user is finnished defining his polygon, and filling a form with username, password, email, etc. all this info gets sent to the controller as soon as the user hits the submit button.
The webapplication is currently being developed on ASP.NET MVC 5 and c# , any help would be really appreciated!

There's essentially 2 ways you can get that data back to the server:
You can put the data into a form element and post that form to an action that's set up to receive it. This will require you to put your username, password, etc into a series of html elements with name attributes set up to follow MVC's conventions (This page has some information on the conventions to use).
You can use jQuery's ajax features to send a raw javascript object containing your data to an MVC action (See this answer and it's linked post for details on how to accomplish this).
In either case, you probably shouldn't be sending a username & password to the server with every request, as you can use an authentication cookie to verify a user's identity once they're logged in to your application (there's plenty of resources online explaining how this works).
For option 2:
Javascript:
var myobject = {
username: "Joe",
password: "password",
points: [{ x: 111.1112, y: 22.2222 },{ x: 11.12, y: 21.11 }]
}
jQuery.ajax({
url: "/MyController/MyAction",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(myobject)
})
C#:
public class PointModel
{
public double x { get; set; }
public double y { get; set; }
}
public class MyModel
{
public string username { get; set; }
public string password { get; set; }
public IList<PointModel> points { get; set; }
}
public class MyController : Controller
{
[HttpPost]
public JsonResult MyAction(MyModel model) {
...
}
}

you can use below java script method to define JavaScript array
<script type="text/javascript">
var array = [];
array.push(10);
array.push(20);
</script>
you use this array to insert points in array and send this array using following Ajax call
var _data = {
'array ': array
};
$.Post(url ,_data, function(data){
})

Related

Serialize form to string and deserealize it later to complex view model

I'm implementing the "Save Draft" functionality on my dynamically generated page and trying to make it as generic as possible. All my controllers and pages should support it and that's why I thought about creating a SaveDraft() POST action in my base controller which will receive a serialized form as a string which can be directly saved into the database and deserialized to a view model later in the specific get action using specific view model
[HttpPost]
public ActionResult SaveDraft(string jsonData, long id)
My first idea was to create the generic base controller and pass the view model type to it but the problem is that some controllers have multiple differently named POST actions and using different view model types, I cant change it now.
Some view models are complex and looking like
public class CollateralsDataModel
{
//...
public List<Applicant> Applicants { get; set; }
}
public class Applicant
{
public long ApplicantId { get; set; }
public IList<RealEstateSecurityCollateralsDTO> RealEstateSecurityCollaterals { get; set; }
public IList<AdditionalCollateralDTO> AdditionalCollaterals { get; set; }
}
public class RealEstateSecurityCollateralsDTO
{
[Required]
[Display(ResourceType = typeof(CollateralsData), Name = nameof(CollateralsData.RealEstateSecurityType))]
public int? RealEstateSecurityTypeId { get; set; }
//...
}
The input names on the form are looking like
"Applicants[0].MortgageApplicantId": "11595",
"Applicants[0].RealEstateSecurityCollaterals[0].Id": "17",
"Applicants[1].MortgageApplicantId": "11596",
"Applicants[1].RealEstateSecurityCollaterals.Index": "0",
"Applicants[1].AdditionalCollaterals[0].Id": "138",
"Applicants[1].AdditionalCollaterals[0].AdditionalCollateralTypeId": "4",
My question is - how can I serialize them to the string so I can deserialize it later?
I tried using different combinations of
$('.draft-data-form').serializeArray()
$('.draft-data-form').serialize()
JSON.stringify($('.draft-data-form').serializeArray());
but in my Action I get the flat JSON structure and I can't deserialize it
var obj = JsonConvert.DeserializeObject<CollateralsDataModel>(jsonData);
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type '...CollateralsDataModel' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
I've also tried to deserialize it as a list but then I get the List of 115 entries
var obj = JsonConvert.DeserializeObject<List<CollateralsDataModel>>(jsonData);
So my question is - how can I serialize them to the string so I can deserialize it later?
You do not want to serialize/deserialize a List. Only a single instance of the model.
I would guess that the error is in instantiating the list within the model. I know that the DataContractSerializer has an issue where if the List is not instantiated to an empty list when the model is constructed then the deserialization is unable to add to it.
Not sure if this is the same problem you are facing but could be worth a try.
eg. use:
public List<Applicant> Applicants { get; set; } = new List<Applicant>();

Jquery Event Calendar and Microsoft Azure problems

I recently asked a question pertaining to my calendar project on here and got good results so I figure ill ask another question about it.
this is the tutorial I am following
http://www.dotnetawesome.com/2017/07/curd-operation-on-fullcalendar-in-aspnet-mvc.html
Unfortunately I lost my code I was working on recently when it comes to this project. But I just wanted to know before I restart coding again: Why do events not load on a calendar(jquery and javascript) when I use an Azure database? Specifically after a posting the events don't load. They will load when I use a regular sql database, but they will not load when using an Azure sql database. I can't find any information on a similar issue and am curious if this is a known issue to do with Json possibly?
Here is a snippet of code that fetches events from the backend:
FetchEventAndRenderCalendar();
function FetchEventAndRenderCalendar() {
events = [];
$.ajax({
type: "GET",
url: "/home/GetEvents",
success: function (data) {
$.each(data, function (i, v) {
events.push({
eventID: v.EventID,
title: v.Subject,
description: v.Description,
start: moment(v.Start),
end: v.End != null ? moment(v.End) : null,
color: v.ThemeColor,
allDay: v.IsFullDay
});
})
I can't debug right now but maybe I will try to enter just part of the code so I can test why exactly using an azure database makes it so events don't load on the calendar.
Why do events not load on a calendar(jquery and javascript) when I use an Azure database?
I download the demo code from you mentioned tutorial. Then I change it to use Azure SQL, and it works correctly.
If we run the application locally, we need to add client IP to Azure SQL firewall to let client to access to the Azure SQL. WE could get more info about Azure SQL firewall from this tutorial.
The following is my details steps:
1.Replace the connectionstring to Azure SQL connectionstring
<connectionStrings>
<add name="MyDatabaseEntities" connectionString="Server=tcp:sqlservername.database.windows.net,1433;Initial Catalog=databasename;Persist Security Info=False;User ID={user};Password={password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" providerName="System.Data.Sqlclient" />
</connectionStrings>
2.Create a table with same schema with given Event table in the Azure sql database.
3.Remove the localdb and MyModel.xx related files
4.Add Event.cs and MyDatabaseEntities.cs file
public class Event
{
public int EventID { get; set; }
public string Subject { get; set; }
public string Description { get; set; }
public System.DateTime Start { get; set; }
public Nullable<System.DateTime> End { get; set; }
public string ThemeColor { get; set; }
public bool IsFullDay { get; set; }
}
public partial class MyDatabaseEntities : DbContext
{
public MyDatabaseEntities()
: base("name=MyDatabaseEntities")
{
}
public virtual DbSet<Event> Events { get; set; }
}
project file struct:
5.Test it locally,it works correctly.

ViewModel current state to JSON

I have an issue with aps.net mvc project. I have a view where is set list of check boxes inside of begin form, then on submit appropriate fields are shown as a report. So I have to add a button to my view, where user is setting which fields he d like to see, so as he could save all checkbox values as a preset with its name.
I have model with a lot of nested models it looks like this:
public class EmployeeOverallReport
{
public List<PersonalData> ListOfPersonalData { get; set; }
public EmployeeOverallReportBool ColumnsNeeded { get; set; }
public EmployeeOverallReportFilters ModelFilters { get; set; }
}
I actually need ColumnsNeeded model, which has alot of bool properties for storing each checkbox value (true/false).
So on click I have to get current state of checkboxes and make a post with these model values.
I have been trying to serialize my form:
var data = $('#myForm').serialize();
$.post(url, { presetName: Name, entry: data}, function (data) {
$("#saveResult").html("Saglabats");
});
I got JSON string but it was invalid and i could not deserialize it back.
Here is what I am trying to do now:
$("#savePresetButton").on('click', function () {
var url = "/Reports/SavePreset";
var data = #Html.Raw(Json.Encode(Model));
$.post(url, { presetName: Name, entry: data}, function (data) {
$("#saveResult").html("Saglabats");
});
});
this code is using my viewModel with its properties, where all ColumnsNeeded properies are set to false, as it is by default and all user side changes in a view are not set to model yet, so as my form was not submitted and values were not changed.
How could I get current state of all checkboxes on user side?
Not doing it like :
var dataset = {
CategoryBool: $("#ColumnsNeeded_CategoryBool").val(),
NameBool: $("#ColumnsNeeded_NameBool").val(),
KnowledgeLevelBool: $("#ColumnsNeeded_KnowledgeLevelBool").val(),
SkillAdditionalInfoBool: $("#ColumnsNeeded_SkillAdditionalInfoBool").val(),
...
}
because I have more than 90 properties there..
I am sorry for this post, but posting some code is impossible due to count of properties inside the model.
Could you serialize the entire form and ajax submit the form itself?
see: Pass entire form as data in jQuery Ajax function

ASP MVC send an Array object to a JavaScript function

I am using ASP MVC for my university coursework. However I have encountered a problem, before I was sending too many AJAX requests which was causing my page to take way too long to load. Therefore I thought I could improve the situation by sending the arrays from the database to the view and then put them into my jquery function inline.
So here is how it looks I have my simple model:
public class NewBooking
{
public IEnumerable<dynamic> parks { get; set; }
}
Then in my controller I set the parks with information from the database as you can see here:
public ActionResult Index()
{
var model = new NewBooking();
var parks = Database.Open("SQLServerConnectionString").Query("SELECT * FROM Park");
var output = from o in parks
select new { parkID = o.parkID, parkName = o.parkName };
model.parks = output.ToList();
return View(model);
}
Now, this returns to the view all the information I am expecting, as you can see below if I simply called the model parks in the view:
#model build_01.Models.Timetabler.NewBooking
#{
#Model.parks
}
I know this method wouldn't however with a for loop it works fine, now to my issue; I'm trying to call a JavaScript function and pass this array to it.
$(document.ready(function () {
slotAvailability(#Model.parks);
}));
Is there something I can do to this #Model.parks to be able to send it to the function? Kind of like how I would do JSON if I was using AJAX.
As it stands trying to call it like this gives me this error in my console:
Uncaught SyntaxError: Unexpected number
I can see why, if I was to inspect element I can see that the function parse looks like this:
slotAvailability(System.Collections.Generic.List`1[<>f__AnonymousType3`2[System.Object,System.Object]]);
Thanks
You should use the Json.Encode function. Also make sure tha you close your parenthesis at the proper place, after document:
$(document).ready(function () {
var parks = #Html.Raw(Json.Encode(Model.parks));
slotAvailability(parks);
});
Also using dynamic seems like a bad design here. You don't get any Intellisense. You'd rather have a view model:
public class ParkViewModel
{
public int ParkId { get; set; }
public int ParkName { get; set; }
}
and then your NewBooking model:
public class NewBooking
{
public IEnumerable<ParkViewModel> Parks { get; set; }
}

Assign new values in a Breeze entity

I'm developing a spa web application with BreezeJS and the DurandalJS Framework. I came accross a problem which I can't fix.
I have a entity called: Car, this entity contains name, number, owner, type en manufacturer. In this entity the name and number are filled in as the entity is created AND saved in the database. The other properties are allowed to be NULL.
This because the other values are filled in during a modal/ dialog screen. Here a user can select a owner from a list and also a type and manufacturer from a list. When the user selects one from a dropdown the selected value should be assigned to the value of the Car entity. How can I get this to work?
Car().Owner = newOwner;
Car.Owner() = newOwner;
This won't work. I tried a lot of combinations. Remember that the value was null first and that I can't insert a new value;S
Edit 1
Here the Entity Framework model of Car
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Estimate_App.Models
{
public class tblCar
{
[Key]
public int CarID { get; set; }
public string CarNumber { get; set; }
private DateTime _CreationDate;
public DateTime CreationDate
{
get { return this._CreationDate; }
set { this._CreationDate = DateTime.Now; }
}
//This is the Owner
[ForeignKey("Owner")]
public int? OwnerID { get; set; }
public tblOwner Owner { get; set; }
}
}
Here is what I put in my Car().Owner(), consider Container should be Car (this is an other project with the same problem)
I hover my mouse over newValue.
Edit 2
By a answer of Julián Yuste I also tried this but it didn't work. Here is the error:
When I do Container().Owner(newValue);
Edit 3
The code that fetches the owners
breeze.EntityQuery.from("Customers")
.using(dataservice.manager)
.execute().then(function (data) {
data.results.forEach(function (item) {
tempCustomerList.push(item); //ko.observableArray([]);
});
}).fail(function (data) {
});
Are you using the EntityManager from your dataservice object in order to create the newOwner object?
In other words, you probably shouldn't be doing this*:
var newOwner = new Owner();
newOwner.OwnerID = 123;
You should do this:
var newOwner = dataservice.manager.createEntity('Owner', { OwnerID: 123 });
*Note that can actually use new Owner(), but that requires you to define entity constructors in your code. :-)
For more information, check out the Breeze documentation: http://www.breezejs.com/documentation/creating-entities
Also, note that you can read the Breeze JavaScript code to help you understand the issue. If you search breeze.debug.js for your error message (An Entity cannot be attached to an entity in another EntityManager. One of the two entities must be detached first.), you will find the line of code that is causing the exception. It may be helpful to backtrack from there.
Edit
The answer to the question was to make sure that the EntityManager object is a Singleton (in this case, the dataservices.manager object).
In other words, use the same EntityManager object to update objects as you use to query for objects.
I think we need more information. Is the 'Owner' property an instance of another entity or is it a primitive type, i.e. string, number etc?
If it is an entity then I would first check that your 'newOwner' variable was also in fact an entity.
If owner is an observable, you need to asign the new value as: owner(newOwner).
Greetings.

Categories

Resources