I have the following viewModel:
public class ProfileLocalizationViewModel
{
public ProfileViewModel Profile { get; set; }
public virtual string LanguageCode { get; set; }
public string Description { get; set; }
}
with the Profile object looking like:
public class ProfileViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsOutlet { get; set; }
public bool IsWholesaler { get; set; }
public bool IsProducer { get; set; }
public List<ProfileLocalizationViewModel> Localizations { get; set; }
}
From the client, I'm sending the following JSON:
{"Profile":{"Id":-1,"Name":"New Profiledsa","IsOutlet":false,"IsWholesaler":false,"IsProducer":false,"Localizations":null},"LanguageCode":"en","Description":"Description for selected language","__ko_mapping__":{"ignore":[],"include":["_destroy"],"copy":[],"observe":[],"mappedProperties":{"Profile.Id":true,"Profile.Name":true,"Profile.IsOutlet":true,"Profile.IsWholesaler":true,"Profile.IsProducer":true,"Profile.Localizations":true,"Profile":true,"LanguageCode":true,"Description":true},"copiedProperties":{}}}
Which gets parsed by Chrome like:
And on the server, when I try to receive a ProfileLocalizationViewModel, the values received are all null:
Any idea why this happens? Any advice greatly appreciated.
Client ajax call:
self.saveProfile = function (model, event) {
model.ItemForEditing.LanguageCode = self.SelectedLanguage.Code().toLowerCase();
var preview = ko.toJSON(model.ItemForEditing);
if (validateForm()) {
$.ajax({
type: "POST",
url: urlSaveProfile,
data: ko.toJSON(model.ItemForEditing),
contentType: 'application/json',
async: true,
beforeSend: function ()
success: function (result) {
// Handle the response here.
self.pushProfile(ko.mapping.fromJS(result.Data));
addContainer.modal('hide');
}
});
}
};
And inside preview, right before the call, there's the JSON...
Related
I cannot figure this out. I have similar code in other areas of my project that works fine. What am I missing?
Why is studentDTO object null?
The Controller Action
[HttpPost("SaveStudent")]
public async Task<IActionResult> SaveStudent(
[Bind(Prefix = "Student")][FromForm] StudentDTO studentDTO
)
{
// blah blah
}
The Class
public class StudentDTO
{
public Guid StudentID { get; set; }
public Guid AccountID { get; set; }
public int TuitionID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public decimal AnnualTuitionCost { get; set; }
public int TuitionMonths { get; set; }
public string StartDate { get; set; }
public string EndDate { get; set; }
}
The AJAX call
var formData = $("#addEditStudentFrm").serialize();
console.log(formData);
$.ajax({
url : '/api/blah/SaveStudent/',
dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: formData,
type: 'POST',
success: function (result) {
// blah blah
},
error: function (result) {
// blah blah
}
});
The Request
I am hitting the controller action, but I'm not getting the form data. Suggestions?
If I remove [FromForm] I get a response of "415 Unsupported Media Type"
I have been using the information provided here to no avail:
https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-6.0
Figured it out. Prefix needed to be Student. and not Student_ in the name attribute of the form elements:
I have an entity that consists of ApllicationUser as a foreign Key:
public class Trades
{
public int ID { get; set; }
public double Price { get; set; }
public double Volume { get; set; }
public string InstrumentName { get; set; }
public ApplicationUser User { get; set; }
}
Then i try to post a trade using AJAX.
var tradeData = {
"Price": 1,
"Volume": 1,
"InstrumentName": "instrumentName",
"User": "#User.Identity.Name"
};
$.ajax({
url: "/api/TradesAPI/",
method: "POST",
data: JSON.stringify(tradeData),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function () {
alert('executed!');
},
error: function (error) {
alert("Transacion has not been executed");
}
});
Unfortunetely ApplicationUser is not being serialised to ApplicationUSer as it is posted a string. What have I done wrong? Thanks for any help in advance.
If we have a class "A" that contains a reference to "B" and this "B" has also a reference to "A" (even if not direct), the proccess of serialization doesn't work. It's like an "infinite loop".
I suggest you change the ApplicationUser(type of User) to string and use it to get the model (on code-behind), if you need it.
If you need to get the user from within the controller, use the User property of Controller.
If you need it from the view, would populate what you specifically need in the ViewData, or you could just call User.
Ex. #User.Identity.Name
Thank you Indrit Kello. I changed my model so I have
public class Trades
{
public int ID { get; set; }
public double Price { get; set; }
public double Volume { get; set; }
public string InstrumentName { get; set; }
public string UserId { get; set; }
}
I decided to take info about user on server in API controller insted of taking data about User in a View.
public void CreateTradeAPI(Trades trade)
{
trade.UserID =User.Identity.Name;
_context.UsersTrades.Add(trade);
_context.SaveChanges();
}
And I have what i wanted :)
I have a list of text boxes, that I get with jquery, I am trying to send them to server side via a model.
I pus a break point on the server side (webmethod) but it won't hit...
Help?
This is the code from the page:
function CreareCont() {
var model = {};
model.Nume = txtNume.val();
model.Prenume = txtPrenume.val();
model.CNPsauCUI = txtCNPsauCUI.val();
model.Strada = txtStrada.val();
model.Numar = txtNumar.val();
model.Etaj = txtEmail.val();
model.Apartament = txtApartament.val();
model.Oras = txtOras.val();
model.SectorSauJudet = txtSectorSauJudet.val();
model.Telefon = txtTelefon.val();
model.Email = txtEmail.val();
model.Parola = txtParola.val();
$.ajax({
type: "POST", url: webservicePageUrl + "/CreareCont",
data: JSON.stringify(model),
contentType: "application/json; charset=utf-8", dataType: "json",
success: OnSuccessCall1, error: OnErrorCall1
});
};
function OnSuccessCall1(response) { alert(response.d); };
function OnErrorCall1(response) { alert(response.status + " " + response.statusText); debugger; };
as I can see from the console, the model send seems to be ok, it's value is:
{"Nume":"asd","Prenume":"asd","CNPsauCUI":"asd","Strada":"asd","Numar":"asd","Etaj":"asd","Apartament":"asd","Oras":"asd","SectorSauJudet":"asd","Telefon":"asd","Email":"asd","Parola":"asdasd123"}
And this is the webservice code:
[WebMethod]
public void CreareCont(Inregistrare user)
{
string hash = helper.GetSHA1HashData("123");
}
The model is a C# class:
public class Inregistrare
{
string Nume { get; set; }
string Prenume { get; set; }
string CNPsauCUI { get; set; }
string Strada { get; set; }
string Numar { get; set; }
string Etaj { get; set; }
string Apartament { get; set; }
string Oras { get; set; }
string SectorSauJudet { get; set; }
string Telefon { get; set; }
string Email { get; set; }
string Parola { get; set; }
}
}
After using fiddler I got this error: {"Message":"Invalid web service call, missing value for parameter: \u0027user\u0027.","StackTrace":" at System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target, IDictionary`2 parameters)\r\n at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary'2 parameters)\r\n at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary'2 rawParams)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}
Your webmethod need to be Static, unless it is in an asmx
public static void CreareCont(Inregistrare user)
and json data need to have the same name of the webmethod´s parameter
data: '{"user":'+ JSON.stringify(model)+ '}'
Include Public in your class properties like public string Nume { get; set; }, it´s need for deserialize json in class object
try this code
js
function CreareCont() {
var model = {};
model.Nume = txtNume.val();
model.Prenume = txtPrenume.val();
model.CNPsauCUI = txtCNPsauCUI.val();
model.Strada = txtStrada.val();
model.Numar = txtNumar.val();
model.Etaj = txtEmail.val();
model.Apartament = txtApartament.val();
model.Oras = txtOras.val();
model.SectorSauJudet = txtSectorSauJudet.val();
model.Telefon = txtTelefon.val();
model.Email = txtEmail.val();
model.Parola = txtParola.val();
$.ajax({
type: "POST", url: webservicePageUrl + "/CreareCont",
data: '{"user":'+ JSON.stringify(model)+ '}',
contentType: "application/json; charset=utf-8", dataType: "json",
success: OnSuccessCall1, error: OnErrorCall1
});
};
cs
[WebMethod]
public static void CreareCont(Inregistrare user)
{
string hash = helper.GetSHA1HashData("123");
}
public class Inregistrare
{
public string Nume { get; set; }
public string Prenume { get; set; }
public string CNPsauCUI { get; set; }
public string Strada { get; set; }
public string Numar { get; set; }
public string Etaj { get; set; }
public string Apartament { get; set; }
public string Oras { get; set; }
public string SectorSauJudet { get; set; }
public string Telefon { get; set; }
public string Email { get; set; }
public string Parola { get; set; }
}
So I have a ViewModel:
public class PrelimViewModel
{
public int? PrelimId { get; set; }
public int JobId { get; set; }
public string Code { get; set; }
public string Description { get; set; }
public string Comment { get; set; }
public string Unit { get; set; }
public int? Qty { get; set; }
public decimal? BidPrice { get; set; }
public bool Accepted { get; set; }
public int? OriginalPrelimId { get; set; }
public string Option { get; set; }
public List<RefCodeViewModel> Codes { get; set; }
public List<UnitViewModel> Units { get; set; }
public List<OptionLetterViewModel> Options { get; set; }
}
A GetPrelim controller method that returns List<PrelimViewModel>
A ko.mapper of the List of PrelimViewModel client side:
viewModel = ko.mapping.fromJS({ Prelims: data });
ko.applyBindings(viewModel);
Do some work, ready to save:
function savePrelims(elem) {
var $form = $(elem).parents('form');
$.ajax({
url: $form.attr('action'),
type: "POST",
data: ko.toJSON(viewModel),
datatype: "json",
contentType: "application/json charset=utf-8",
success: function(data) { toastr.success('Options Saved!'); },
error: function(data) { }
});
}
And I cannot get my MVC Method to parse the JSON:
public void AddPrelims(List<PrelimViewModel> Prelims)
You have wrapped your list into the Prelims property in your KO viewmodel, but on the server side you are expecting just a list not with an object which has the list in its Prelims property.
So to fix this you just need to send the list in your ajax request:
data: ko.toJSON(viewModel.Prelims()),
However you don't necessary need to wrap your list if you won't have any additional properties on your viewmodel, because you can just do:
viewModel = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);
And then in your view you can bind to $data which is refering the current viewmodel which will be your array:
<div data-bind="foreach: $data">
...
</div>
And in this case you don't have to change your ajax call and data: ko.toJSON(viewModel), should work fine.
However this foreach: $data is kinda strange and it is not the best solution so you are probably better if you stick to your original approach with ko.mapping.fromJS({ Prelims: data }); and sending the correct data back to your controller.
I am working on an ASP.NET MVC application. I have the following view model in c#:
public class ContactModel
{
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
}
public class PersonModel
{
public ContactModel Contact;
public PersonModel()
{
Contact = new ContactModel();
}
public string FirstName { get; set; }
public string LastName { get; set; }
public string Profession { get; set; }
}
Now i have the same json model at client side which i want to post to server. I am using following jquery ajax:
$.ajax({
url: "address to controller",
type: "post",
data: JSON.stringify(data),
contentType: "application/json",
success: function () {
alert("data saved successfully");
}
});
But only PersonModel properties are get mapped but Contact properties are null. Can anybody please tell me what i am missing??
You need for format your string to proper json -
Say if you model is -
public class ContactModel
{
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
}
public class PersonModel
{
public ContactModel Contact { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Profession { get; set; }
}
Then you AJAX Post should be like this -
<script>
$(function () {
$('#click1').click(function (e) {
var studentData = {
"FirstName": "Rami",
"LastName": "Vemula" ,
"Contact": { "City": "Hyd"}
};
$.ajax({
url: "#Url.Action("Submit")",
type: "POST",
data: JSON.stringify(studentData),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (response) {
alert(response.responseText);
},
success: function (response) {
alert(response);
}
});
});
});
</script>
Then output is going to be -
Create a instance of ContactModel and assign it to contact under PersonModel after creating instance of PersonModel.
Please let me know in case of any clarification needed
If you are using #html helper for properties then form.serialize() method will bind all the properties otherwise if you are using html elements like <input> the assign their name property same as model property.
<input type="text" name="Contact.FirstName" value="#Model.Contact.FirstName"/>