SignalR for some reason fails when I try to send an object from client to be represented in a complex class.
The below client-side code works fine...
connection.send("ABC", "111", "222", { text: "text" }).then(() => console.log("sent")).catch((r) => console.log(r))
...for the below server-side code
public async Task ABC(string a, string b, User c)
{
await Clients.All.SendAsync(RECEIVE, a, b, c);
}
public class User
{
public string Text { get; set; }
public string Name { get; set; }
}
The below doesn't work....
connection.send("ABC", "111", "222", { text: "text", jsonOptions: [] }).then(() => console.log("sent")).catch((r) => console.log(r))
...for the below server side code
public async Task ABC(string a, string b, Post c)
{
await Clients.All.SendAsync(RECEIVE, a, b, c);
}
public class Post
{
public int Id { get; set; }
[Required] [StringLength(450, ErrorMessage = "Sender id cannot be more than 450")]
public string SenderId { get; set; }
[Required] [StringLength(30, ErrorMessage = "Sender name cannot be more than 30")]
public string SenderName { get; set; }
[StringLength(300, ErrorMessage = "Senderpic length must not be more than 300")]
public string SenderPic { get; set; }
public PostLocation PostLocation { get; set; }
public int? CourseId { get; set; }
public int ClassId { get; set; }
public int? ChatId { get; set; }
public int? LectureId { get; set; }
[Required] [StringLength(2000, ErrorMessage = "Post text cannot be more than 2000")]
public string Text { get; set; }
[Required]
public DateTimeOffset TimeStamp { get; set; }
[NotMapped]
public int Upvotes { get; set; }
[NotMapped]
public ICollection<string> UpvoteIds { get; set; }
[NotMapped]
public ICollection<string> DownvoteIds { get; set; }
[NotMapped]
public ICollection<string> StarredIds { get; set; }
public PostType Type { get; set; }
public bool IsReply { get; set; }
[ForeignKey(nameof(FullRepliedPost))]
public int? RepliedId { get; set; }
[NotMapped]
public MiniPost RepliedPost { get; set; }
[StringLength(300, ErrorMessage = "ProfilePicturePath length must not be more than 300")]
public string AttachmentPath { get; set; }
public AttachmentType AttachmentType { get; set; }
public int AnsweredPostId { get; set; }
public Choice CorrectAnswer { get; set; }
public string JsonOptions { get; set; }
[NotMapped]
public ICollection<string> Options => (ICollection<string>)
JsonConvert.DeserializeObject(JsonOptions, typeof(ICollection<string>));
[NotMapped]
public ICollection<string> ASelectionIds { get; set; }
[NotMapped]
public ICollection<string> BSelectionIds { get; set; }
[NotMapped]
public ICollection<string> CSelectionIds { get; set; }
[NotMapped]
public ICollection<string> DSelectionIds { get; set; }
[NotMapped]
public ICollection<string> ESelectionIds { get; set; }
#region navigation properties
[JsonIgnore]
public Post FullRepliedPost { get; set; }
[JsonIgnore]
public ICollection<PostVote> PostVotes { get; set; }
[JsonIgnore]
public ICollection<PostStar> PostStars { get; set; }
[JsonIgnore]
public ICollection<MultiChoice> OptionSelections { get; set; }
[JsonIgnore] [ForeignKey(nameof(RepliedId))]
public ICollection<Post> Replies { get; set; }
#endregion
}
I use the above Post class as a business object, that's why it has all those attributes. I wonder if that has something to do with the failure. I get the below error in Chrome dev tools
[2020-11-07T20:19:42.768Z] Information: Connection disconnected.
and when I try to send again, I get an error saying that I can't send messages when signalR is disconnected.
EDIT: I omitted something in the code I pasted here (jsonOptions: []), which turned out to be the actual cause of the problem.
It turns out the problem was entirely my fault. The JsonOptions property in the entity class should be a string, but I was sending an array from the client. Replacing jsonOptions: [] with jsonOptions: "[]" fixed it and it serialized fine.
Regardless, I've decided to just send the Id of the Post object instead of the whole object. I think it's going to be more efficient that way.
I recently added a new model to my MVC application that looks like this
namespace PIC_Program_1._0.Models
{
public class DisposalOrder
{
[Key]
[Display(Name = "DO ID")]
public int ID { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Date Created")]
public DateTime DateCreated { get; set; }
[DefaultValue("Pending")]
public DOStatus Status { get; private set; }
public decimal disposed { get; set; }
public string Details { get; set; }
public virtual ICollection<DODetails> DisposalDetails { get; set; }
public virtual Site sites { get; set; }
public virtual Component Components { get; set; }
public virtual Item Items { get; set; }
public virtual Part Parts { get; set; }
public bool deleted { get; set; }
public bool hasBeenReleased { get; set; }
public string Notes { get; private set; }
}
}
But when I run a add-migration and an update database, nothing is changed.
I created the model by right-clicking my Models folder, then typing "Add class" so it should be setup the right way. I'm stumped as to why it's not adding?
How to pass model with Kendo Window refresh option ?
I am using below code for that in my partial view:-
var proWindow = $("#productWindow").data("kendoWindow");
proWindow.refresh({
url: "../../Product/UpdateProduct",
type: "POST",
contentType:"application/json",
data: { prodModel: $("form").serialize()
});
And below is the code for Controller:-
[HttpPost]
public ActionResult UpdateProduct(ProductMaintViewModel prodModel)
{
}
But i am getting null on my model parameter in controller.
Can any one have any idea about that,means how we can post the whole model with kendo window refresh data option in jquery/javascript ?
FYI, i am working on ASP.NET MVC 4 application.
Below is my ProductMaintViewModel class :-
public class ProductMaintViewModel
{
[HiddenInput(DisplayValue = false)]
public int ProductID { get; set; }
public int? CustomerId { get; set; }
public int? InsuranceId { get; set; }
[Required]
[StringLength(50)]
[Remote("CheckProductName", "Product", ErrorMessage = "Product Name already exists.")]
[Display(Name = "Name")]
public string Name { get; set; }
[StringLength(100)]
[Display(Name = "Description")]
public string Description { get; set; }
public bool IsDraft { get; set; }
[Required]
[Display(Name = "Product Type")]
public int? SelectedProductTypeID { get; set; }
public IEnumerable<SelectListItem> ProductTypes { get; set; }
public bool IsDeleted { get; set; }
[Display(Name = "Customer Type")]
public int? SelectedCustomerSubTypeId { get; set; }
public IEnumerable<SelectListItem> CustomerSubTypes { get; set; }
public IEnumerable<SelectListItem> AvailableLabor { get; set; }
}
How I define my model using lazyloading = true in MVC 4? I am trying to load my foreign keys. Now my query is coming null. In my web api query comes right.
I did not use the "virtual".
My Model:
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int intClienteFornecedorId { get; set; }
[MaxLength(50)]
[Display(Name = "Nome:")]
[UniqueClienteFornecedorNome(ErrorMessage = "Já existe um Cliente ou Fornecedor cadastrado com esse Nome.")]
[Required(ErrorMessage = "É obrigatório informar o Nome.")]
public string strClienteFornecedorNome { get; set; }
[MaxLength(2)]
[Display(Name = "Pessoa:")]
public string strClienteFornecedorPessoa{ get; set; }
[ForeignKey("Estado")]
[Display(Name = "Estado:")]
public string strUFId { get; set; }
public virtual Estado Estado { get; set; }
[MaxLength(9)]
[Display(Name = "CEP:")]
public string strClienteFornecedorCEP { get; set; }
[MaxLength(70)]
[Display(Name = "Site:")]
public string strClienteFornecedorSite { get; set; }
[MaxLength(250)]
[Display(Name = "Observação:")]
public string strClienteFornecedorObservacao { get; set; }
[MaxLength(1)]
[Display(Name = "Situação:")]
public string strClienteFornecedorSituacao { get; set; }
[ForeignKey("Usuario")]
public int intUsuarioId { get; set; }
public virtual Usuario Usuario { get; set; }
public DateTime? dtClienteFornecedorDataAlteracao { get; set; }
public DateTime? dtClienteFornecedorDataCriacao { get; set; }
[NotMapped]
public bool ckbClienteFornecedor { get; set; }
[NotMapped]
public bool? hdMaisInformacoes { get; set; }
[NotMapped]
public bool? hdObservacao { get; set; }
public virtual ICollection<Contato> Contatos { get; set; }
public virtual ICollection<ClienteFornecedor_Contato> ClienteFornecedoresContatos { get; set; }
WEB API:
[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, false)]
public List<ClienteFornecedor> GetClientesFornecedoresByintUsuarioId(int intUsuarioId)
{
//Validate Input
if (intUsuarioId.IsEmpty())
return GetAllClienteFornecedor();
_DatabaseContext.ContextOptions.LazyLoadingEnabled = false;
return (from clienteFornecedor in _DatabaseContext.ClienteFornecedor
where clienteFornecedor.intUsuarioId == intUsuarioId
select clienteFornecedor).Include("Usuario").Include("UF").OrderBy(c => c.strClienteFornecedorNome).ToList();
}
In the web api returns two records, but in my web application the second record returns null why?
Could anyone help me please?
The second record is null, anyone know why?
JSON:
[{"$id":"1","intClienteFornecedorId":8,"strClienteFornecedorNome":"CPFL","strClienteFornecedorPessoa":"PJ","strClienteFornecedorCPF":null,"strClienteFornecedorCNPJ":"11.111.111/1111-11","strClienteFornecedorTelefone":null,"strClienteFornecedorTelefone2":null,"strClienteFornecedorEmail":null,"strClienteFornecedorEndereco":null,"strClienteFornecedorComplemento":null,"strClienteFornecedorBairro":null,"strClienteFornecedorCidade":"SP","strUFId":"SP","strClienteFornecedorCEP":null,"strClienteFornecedorSite":null,"strClienteFornecedorObservacao":null,"strClienteFornecedorSituacao":"A","intUsuarioId":1,"dtClienteFornecedorDataAlteracao":"2013-10-30T11:29:33.303","dtClienteFornecedorDataCriacao":"2013-10-30T11:29:33.303","Categoria":[],"UF":{"$id":"2","strUFId":"SP","strUFNome":"São Paulo","Contato":[],"ClienteFornecedor":[{"$ref":"1"}],"EntityKey":{"$id":"3","EntitySetName":"UF","EntityContainerName":"DatabaseContext","EntityKeyValues":[{"Key":"strUFId","Type":"System.String","Value":"SP"}]}},"Usuario":{"$id":"4","intUsuarioId":1,"strUsuarioNome":"Danielle Ramos Tonhai","strUsuarioEmail":"danielle.ramos#unidax.com.br","strUsuarioSenha":"12345678","strUsuarioAdministrador":"S","strUsuarioSituacao":"A","intUsuarioPaiId":0,"dtUsuarioDataAlteracao":"2013-10-28T15:16:28.233","dtUsuarioDataCriacao":"2013-10-24T16:42:26","bitUsuarioConfirmado":true,"CartaoCredito":[],"Categoria":[],"ContaBancaria":[],"ContaContabil":[],"Contato":[],"Entidade":[],"Evento":[],"FormaPagamento":[],"ClienteFornecedor":[{"$ref":"1"},{"$id":"5","intClienteFornecedorId":9,"strClienteFornecedorNome":"Danielle","strClienteFornecedorPessoa":"PF","strClienteFornecedorCPF":"111.111.111-11","strClienteFornecedorCNPJ":null,"strClienteFornecedorTelefone":null,"strClienteFornecedorTelefone2":null,"strClienteFornecedorEmail":null,"strClienteFornecedorEndereco":null,"strClienteFornecedorComplemento":null,"strClienteFornecedorBairro":null,"strClienteFornecedorCidade":null,"strUFId":null,"strClienteFornecedorCEP":null,"strClienteFornecedorSite":null,"strClienteFornecedorObservacao":null,"strClienteFornecedorSituacao":"A","intUsuarioId":1,"dtClienteFornecedorDataAlteracao":"2013-10-30T11:29:52.203","dtClienteFornecedorDataCriacao":"2013-10-30T11:29:52.203","Categoria":[],"UF":null,"Usuario":{"$ref":"4"},"Contato":[],"EntityKey":{"$id":"6","EntitySetName":"ClienteFornecedor","EntityContainerName":"DatabaseContext","EntityKeyValues":[{"Key":"intClienteFornecedorId","Type":"System.Int32","Value":"9"}]}}],"EntityKey":{"$id":"7","EntitySetName":"Usuario","EntityContainerName":"DatabaseContext","EntityKeyValues":[{"Key":"intUsuarioId","Type":"System.Int32","Value":"1"}]}},"Contato":[],"EntityKey":{"$id":"8","EntitySetName":"ClienteFornecedor","EntityContainerName":"DatabaseContext","EntityKeyValues":[{"Key":"intClienteFornecedorId","Type":"System.Int32","Value":"8"}]}},{"$ref":"5"}]
I have three model classes and three views. Models are given below
public class BASLPApplicationFormModel
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int BASLPApplicationID { get; set; }
public string BASLPApplicationNo { get; set; }
public string ApplicantName { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Date of Birth", Prompt = "DD/MM/YYYY")]
public DateTime DateOfBirth { get; set; }
[Required]
[Display(Name = "Email-ID")]
public string EmailID { get; set; }
}
and second
public class DPPHIApplicationFormModel
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int DPPHIApplicationID { get; set; }
public string DPPHIapplicationNo { get; set; }
[Required]
[Display(Name = "Name of Applicant")]
[DataType(DataType.Text)]
public string Name { get; set; }
[Required]
[Display(Name = "Expansion of Initial")]
[DataType(DataType.Text)]
public string InitialExpansion { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Date of Birth", Prompt = "MM/DD/YYYY")]
public DateTime DateOfBirth { get; set; }
[Required]
[Display(Name = "Email-ID")]
[DataType(DataType.EmailAddress)]
public string EmailID { get; set; }
}
and third
public class DTYDHHApplicationFormModel
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int DTYDHHApplicationID { get; set; }
public string DTYDHHAapplicationNo { get; set; }
[Required]
[Display(Name = "Name of Applicant")]
[DataType(DataType.Text)]
public string name { get; set; }
[RegularExpression("^([0-9]+)$", ErrorMessage = "Invalid Phone Number")]
[DataType(DataType.PhoneNumber)]
[Display(Name = "Land Line Number")]
public string Phone { get; set; }
[Required]
[Display(Name = "Email-ID")]
[DataType(DataType.EmailAddress)]
public string EmailID { get; set; }
}
Email model ,
[Table("Emails")]
public class UserEmails
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string UserEmailID { get; set; }
}
Here user interacts with any of the forms and submitting their forms accordingly.
I would like to get all Email entries to my Emails table using code first approach and please advice me how can achieve.
Take a look at this serie of three blogposts:
http://weblogs.asp.net/manavi/archive/2010/12/24/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-1-table-per-hierarchy-tph.aspx
http://weblogs.asp.net/manavi/archive/2010/12/28/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-2-table-per-type-tpt.aspx
http://weblogs.asp.net/manavi/archive/2010/12/24/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-1-table-per-hierarchy-tph.aspx
Hope this helps