Httpget Method using asp.net mvc in controller - asp.net-mvc

Fetch data from database some error occur here (AdminPurpose con = i.a ) Message show Cannot implicitly converted type.Please see below for my code snippets:
public JsonResult GetInfor()
{
List<AdminPurpose> all = new List<AdminPurpose>();;
using (db_Hajj_UmrahEntities dc= new db_Hajj_UmrahEntities()) {
var datas = (from a in dc.Duas join b in dc.Purposes on a.PurposeId equals b.Id
select new {
a,
b.PurPose1
});
if(datas != null) {
foreach (var i in datas)
{
AdminPurpose con = i.a ;
con.PurPose1 = i.PurPose1;
all.Add(con);
}
}
}
return new JsonResult { Data = all, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
Model class one to many relation here it's using
[MetadataType(typeof(DuaMetaData))]
public partial class AdminPurpose
{
public string PurPose1 { get; set; }
}
public class DuaMetaData
{
public string Dua_Name { get; set; }
public string Arabic_Word { get; set; }
public string Translation_English { get; set; }
public string Source { get; set; }
[Display(Name = "Purpose")]
public int PurposeId { get; set; }
}

Related

how to return json data from mvc controller and view

I am new to mvc so here is my problem I have created a jquery-datatble with a action link named "detalles". When a user clicks on it I what to be able to see the details of the item selected in the jquery-datatble. Once the user has clicked on it. It opens a new tab that has a form with fields and also an other jquery-datatble. Basicly my idea would be to only have one return in the controler that return the view and th json.
Here is my Action result for i "detalles"
public ActionResult Detalles(int? id)
{
proveedorContext proveedorContext = new proveedorContext();
if (id == null)
{
}
proveedorModel proveedor = proveedorContext.GetAllProveedor().Find(obj => obj.proveedor_id == id);
//When i am here my model is not empty
loadProveedorContactoTable(proveedor);
if (proveedor == null)
{
}
return View(proveedor);
}
But unfortunately after words my program calls "loadProveedorContactoTable" again and then my model is completely null
public ActionResult loadProveedorContactoTable(proveedorModel model)
{
try
{
var proveedorsContactoData = model.contactos.OrderBy(a => a.nombre_contacto).ToList();
return Json(new { data = proveedorsContactoData }, JsonRequestBehavior.AllowGet);
}
catch
{
return View();
}
}
Here is my proveedorModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace erp_colombia.Models
{
public class proveedorModel
{
public int proveedor_id { get; set; }
public string nombre { get; set; }
public string direccion { get; set; }
public string codigo_postal { get; set; }
public string cuidad { get; set; }
public string pais { get; set; }
public string pagina_internet { get; set; }
public int compras_cantidad { get; set; }
public int componente_cantidad { get; set; }
public int eliminado { get; set; }
public List<ContactoModel> contactos { get; set; }
}
}
And here is how I read the data for contactos and proveedor()
public List<proveedorModel> GetAllProveedor()
{
List<proveedorModel> list = new List<proveedorModel>();
using (MySqlConnection conn = GetConnection())
{
conn.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * FROM erp_proveedores",conn);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
list.Add(new proveedorModel()
{
proveedor_id = int.Parse(reader.GetString(reader.GetOrdinal("proveedor_id"))),
nombre = reader.GetString(reader.GetOrdinal("nombre")),
direccion = reader.GetString(reader.GetOrdinal("direccion")),
codigo_postal = reader.GetString(reader.GetOrdinal("codigo_postal")),
cuidad = reader.GetString(reader.GetOrdinal("cuidad")),
pais = reader.GetString(reader.GetOrdinal("pais")),
pagina_internet = reader.GetString(reader.GetOrdinal("pagina_internet")),
eliminado = int.Parse(reader.GetString(reader.GetOrdinal("eliminado"))),
contactos = new proveedorContactoContext().GetAllProveedorContactos(int.Parse(reader.GetString(reader.GetOrdinal("proveedor_id"))))
});
}
}
return list;
}
}
What can I do to fix this problem thank you for your help. I am thinking about making one return that would return the json and the view how could I so thar

Cannot insert the value NULL into column from unrelated entity

I'm getting a "Cannot insert null into column" error from an unrelated table when trying to add a new record for the "original" table.
I have the following two (relevant) entities:
public class Complex
{
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
public Guid OwnerId { get; set; }
[ForeignKey("OwnerId")]
public Owner Owner { get; set; }
public Guid AddressId { get; set; }
[ForeignKey("AddressId")]
public virtual Address Address { get; set; }
public virtual ICollection<Unit> Units { get; set; }
public virtual ICollection<StaffMember> StaffMembers { get; set; }
public Complex()
{
this.Id = System.Guid.NewGuid();
this.Units = new HashSet<Unit>();
this.StaffMembers = new HashSet<StaffMember>();
}
public void AddUnit(Unit unit)
{
Units.Add(unit);
}
public void AddStaff(StaffMember staffMember)
{
StaffMembers.Add(staffMember);
}
}
and
public class Owner
{
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
public Guid ContactInfoId { get; set; }
[ForeignKey("ContactInfoId")]
public ContactInfo ContactInfo { get; set; }
public ICollection<StaffMember> Employees { get; set; }
public ICollection<Complex> Complexes { get; set; }
public Owner()
{
this.Id = System.Guid.NewGuid();
this.Employees = new HashSet<StaffMember>();
this.Complexes = new HashSet<Complex>();
}
public void AddEmployee(StaffMember employee)
{
Employees.Add(employee);
}
public void AddComplex(Complex complex)
{
Complexes.Add(complex);
}
}
I'm trying to add a new owner in the following code:
if (ModelState.IsValid)
{
Owner newOwner = new Owner();
ContactInfo newContactInfo = new ContactInfo();
Address newAddress = new Address();
newAddress.Address1 = viewModel.ContactInfo.Address.Address1;
newAddress.Address2 = viewModel.ContactInfo.Address.Address2;
newAddress.City = viewModel.ContactInfo.Address.City;
newAddress.State = viewModel.ContactInfo.Address.State;
newAddress.Zip = viewModel.ContactInfo.Address.Zip;
newContactInfo.Address = newAddress;
newContactInfo.Email = viewModel.ContactInfo.Email;
newContactInfo.Phone1 = viewModel.ContactInfo.Phone1;
newContactInfo.Phone2 = viewModel.ContactInfo.Phone2;
newOwner.Name = viewModel.Name;
newOwner.ContactInfo = newContactInfo;
using (REMSDAL dal = new REMSDAL())
{
dal.Owners.Add(newOwner);
var result = await dal.SaveChangesAsync();
if (result > 0)
{
viewModel.ActionStatusMessageViewModel.StatusMessage = "Owner " + viewModel.Name + " added.";
viewModel.Name = "";
return View(viewModel);
}
}
}
...but getting this error:
Exception Details: System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'OwnerId', table 'REMS.dbo.Complexes'; column does not allow nulls. UPDATE fails.
The statement has been terminated.
How can I be getting an error regarding Complexes when I'm trying to add an Owner?

How to retrieve list of data in model

I have data in model and I used to store that data in session as below in controller
if (providerListingModel.ServiceDetails != null && providerListingModel.ServiceDetails.Count > 0)
Session["ServiceDetails"] = providerListingModel.ServiceDetails;
else
Session["ServiceDetails"] = null;
and for retrieving I had used the logic as
if (Session["ServiceDetails"] != null)
{
if (providerListingModel.ServiceDetails == null)
{
List<ServiceDetail> sam = (List<ServiceDetail>)Session["ServiceDetails"];
foreach (var items in sam)
{
var sd = new ServiceDetail();
sd.Id = items.Id;
sd.CategoryServiceId = items.CategoryServiceId;
sd.ServiceType = items.ServiceType;
sd.ServicePrice = items.ServicePrice;
sd.IsSelected = items.IsSelected;
sd.ProviderListingId = providerListingModel.ProviderListingId;
providerListingModel.ServiceDetails.Add(sd);
}
}
Session["ServiceDetails"] = null;
}
The session contains data but on providerListingModel.ServiceDetails.Add(sd); it throw null exception.
ServiceDetails is a class and it contains list of items
namespace xyz.DAL
{
using System;
using System.Collections.Generic;
public partial class ServiceDetail
{
public int Id { get; set; }
public int ProviderListingId { get; set; }
public Nullable<int> CategoryServiceId { get; set; }
public string ServiceType { get; set; }
public Nullable<int> ServicePrice { get; set; }
public string CustomeService { get; set; }
public Nullable<bool> IsSelected { get; set; }
public virtual CategoryService CategoryService { get; set; }
public virtual ProviderListing ProviderListing { get; set; }
}
}
am I missing some code?
As I am new I don't know what I am doing wrong
You are inserting the item to null value, so it throws an error. Create new instance of the list and add an item to collection.
if(providerListingModel.ServiceDetails ==null)
providerListingModel.ServiceDetails = new List<ServiceDetail>();

Facebook Ad Leads retrieval asp.net

Is there a way I can read Ad leads data from Lead_ID in asp.net? I see there are examples of PHP but there is no SDK for C#.Unforunately I have to use Asp.net and cannot use any other technologies
Any suggestions are highly appreciated
You can use facebook sdk c# and
var fb = new FacebookClient
{
AccessToken ="token"
};
var json = fb.Get("page_id or ad_id/leadgen_forms");
var forms = JsonConvert.DeserializeObject<FormsLeads>(json.ToString());
foreach (var form in forms.data)
{
var jsonre = fb.Get(form.id + "/leads");
var leads = JsonConvert.DeserializeObject<Leads>(jsonre.ToString());
while (leads.paging != null)
{
foreach (var lead in leads.data)
{
var leadnovo = new Models.Lead();
leadnovo.CamposExtras.Add(new CampoExtra { Nome = "idfacebook", Valor = lead.id });
leadnovo.DataCadastro = lead.created_time;
foreach (var t in lead.field_data)
{
if (t.name == "full_name")
{
leadnovo.Nome = t.values.FirstOrDefault();
}
else
if (t.name == "email")
{
leadnovo.Email = t.values.FirstOrDefault();
}
else
if (t.name == "phone_number")
{
leadnovo.Celular = t.values.FirstOrDefault();
}
else
{
leadnovo.CamposExtras.Add(new CampoExtra()
{
Nome = t.name,
Valor = t.values.FirstOrDefault()
});
}
}
if (db.Leads.FirstOrDefault(c => c.Email == leadnovo.Email) == null)
{
db.Leads.Add(leadnovo);
db.SaveChanges();
}
}
if (leads.paging != null)
{
jsonre = fb.Get(form.id + "/leads?after=" + leads.paging.cursors.after);
leads = JsonConvert.DeserializeObject<Leads>(jsonre.ToString());
}
}
}
}
Class for deserialize
public class Cursors
{
public string before { get; set; }
public string after { get; set; }
}
public class Field_Data
{
public string name { get; set; }
public string[] values { get; set; }
}
public class FormsLeads
{
public Formulario[] data { get; set; }
public Paging paging { get; set; }
}
public class Formulario
{
public string id { get; set; }
public string leadgen_export_csv_url { get; set; }
public string locale { get; set; }
public string name { get; set; }
public string status { get; set; }
}
public class Lead
{
public DateTime created_time { get; set; }
public string id { get; set; }
public Field_Data[] field_data { get; set; }
}
public class Leads
{
public Lead[] data { get; set; }
public Paging paging { get; set; }
}
public class Paging
{
public Cursors cursors { get; set; }
}

Update existing entity framework with database (by adding new tables from db)

Hi i have an entity and i am gonna add two tables from database named as country and state.
There is a relation between these two tables based on CountryId.
I used the "Update Model from database ..." to add these two entity types.
I have manually written two classes for these two entity-types given as below:-
public partial class Country
{
//[Key] //[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int CountryID { get; set; }
public string CountryName { get; set; }
}
public partial class State
{
public int StateID { get; set; }
public string StateName { get; set; }
public int CountryID { get; set; }
}
public DbSet<Country> Countries { get; set; }
public DbSet<State> States { get; set; }
Controller to fetch coutries and states :-
public JsonResult GetCountries()
{
List<Country> allCountry = new List<Country>();
using (SunilEntities dc = new SunilEntities())
{
allCountry = dc.Countries.OrderBy(a => a.CountryName).ToList();
}
return new JsonResult { Data = allCountry, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
public JsonResult GetStates(int countryID)
{
List<State> allState = new List<State>();
using (SunilEntities dc = new SunilEntities())
{
allState = dc.States.Where(a => a.CountryID.Equals(countryID)).OrderBy(a => a.StateName).ToList();
}
return new JsonResult { Data = allState, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
But I am getting an error "The entity type Country is not part of the model for the current context".
What should be the exact classes to be used to use these two tables in my controller?
Is there any way I can get automated classes after entity being updated with newer tables?
Under your yourmodel.edmx file there is yourmodel.tt and it generates relevant classes, thus there is no need to write these classes. By using relevant namespace you can use them.
I got the solution change models as below:-
public partial class Country
{
public Country()
{
this.States = new HashSet<State>();
}
public int CountryID { get; set; }
public string CountryName { get; set; }
public virtual ICollection<State> States { get; set; }
}
public partial class State
{
public int StateID { get; set; }
public string StateName { get; set; }
public Nullable<int> CountryID { get; set; }
public virtual Country Country { get; set; }
public virtual State State1 { get; set; }
public virtual State State2 { get; set; }
}
and change controller as given below:-
public JsonResult GetCountries()
{
using (SunilEntities dc = new SunilEntities())
{
var ret = dc.Countries.Select(x => new { x.CountryID, x.CountryName }).ToList();
return Json(ret, JsonRequestBehavior.AllowGet);
}
}
// Fetch State by Country ID
public JsonResult GetStates(int countryID)
{
using (SunilEntities dc = new SunilEntities())
{
var ret = dc.States.Where(x => x.CountryID == countryID).Select(x => new { x.StateID, x.StateName }).ToList();
return Json(ret, JsonRequestBehavior.AllowGet);
}
}

Resources