manish.communityhub Ответов: 0

Метод Post возвращает нулевые значения в web api с помощью angular 4


Вот мой метод сохранения в файле ts:

SaveProject() {
   this.project.ProjectId = 0;
   this.project.ProjectManager = parseInt(this._ProjectManager.toString());
   this.project.ProjectLeader = parseInt(this._ProjectLeader.toString());
   this.project.ClientId = parseInt(this._Client.toString());
   this.project.ProjectType = parseInt(this._ProjectType.toString());
   if (this.validateModel())
     this.projectService.SaveProject(this.project)
       .subscribe(
       empList => { this.returnProject = empList; this.showSuccess(); this.GetProjectList(); this.clear(); },
       error => { this.errorMessage = <any>error; alert(error); });
 }


служебный файл

SaveProject(project: Project): Observable<Project> {
  let bodyString = JSON.stringify(project); // Stringify payload
  let headers = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
  let options = new RequestOptions({ headers: headers }); // Create a request option
  console.log(bodyString);
  return this.http.post(this.rootUrl + '/SaveProject', bodyString, options) // ...using post request
    .map((res: Response) => res.json()) // ...and calling .json() on the response to return data
    .catch((error: any) => Observable.throw(error.json().error || 'Server error')); //...errors if any
}


Класс Api


public class Project
    {
        int ProjectId { get; set; }
        int ClientId { get; set; }
        string ClientName { get; set; }
        string ProjectName { get; set; }
        int ProjectType { get; set; }
        string ProjectTypeName { get; set; }
        string ClientConcernPerson { get; set; }
        string ContactNo { get; set; }
        string GivenDate { get; set; }
        string DeliveryDate { get; set; }
        int ProjectManager { get; set; }
        int ProjectLeader { get; set; }
        string ProjectManagerName { get; set; }
        string ProjectLeaderName { get; set; }
        //List<ProjectMgr> ProjectMgrList { get; set; }
        //List<TeamLdr> TeamLdrList { get; set; }
        //List<ClientListForDropdownList> ProjectClientList{get;set;}

        SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString());
      
        public List<Project> GetProjectList(int ProjectId)
        {
            SqlCommand cm = new SqlCommand("GetProjectList", cn);
            cm.Parameters.AddWithValue("@Projectid", ProjectId);
            cm.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(cm);
            DataTable dt = new DataTable();
            da.Fill(dt);
            List<Project> projectList = new List<Project>();
            Client C=new Client();
            foreach (DataRow dr in dt.Rows)
            {
                projectList.Add(new Project
                {
                    ProjectId = Convert.ToInt32(dr["ProjectId"].ToString()),
                    ProjectLeader = Convert.ToInt32(dr["ProjectLeader"].ToString()),
                    ProjectName = dr["ProjectName"].ToString(),
                    ProjectType = Convert.ToInt32(dr["ProjectType"].ToString()),
                    ProjectTypeName = dr["ProjectTypeName"].ToString(),
                    ClientId = Convert.ToInt32(dr["ClientId"].ToString()),
                    ClientName = dr["ClientName"].ToString(),
                    ClientConcernPerson = dr["ClientConcernPerson"].ToString(),
                    ContactNo = dr["ContactNo"].ToString(),
                    GivenDate = dr["GivenDate"].ToString(),
                    DeliveryDate = dr["DeliveryDate"].ToString(),
                    ProjectManager = Convert.ToInt32(dr["ProjectManager"].ToString()),
                    ProjectManagerName = dr["ProjectManagerName"].ToString(),
                    ProjectLeaderName = dr["ProjectLeaderName"].ToString(),
                    //ProjectMgrList = GetProjectMgrList(),
                    //TeamLdrList = GetTeamLdrList(),
                    //ProjectClientList=GetClientListForDropdownList()
                });

            }
            return projectList;
        }
        
        public List<ClientListForDropdownList> GetClientListForDropdownList()
        {
            ClientListForDropdownList c = new ClientListForDropdownList();
            SqlCommand cm = new SqlCommand("GetClientForddl", cn);
            cm.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(cm);
            DataTable dt = new DataTable();
            da.Fill(dt);
            List<ClientListForDropdownList> cclist = new List<ClientListForDropdownList>();
            foreach (DataRow dr in dt.Rows)
            {
                cclist.Add(new ClientListForDropdownList
                {
                    ClientID = Convert.ToInt32(dr["ClientRowID"].ToString()),
                    ClientName = dr["ClientName"].ToString()
                });
            }
            return cclist;
        }
        public List<TeamLdr> GetTeamLdrList()
        {
            SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString());
            SqlCommand cm = new SqlCommand("GetTeamLdrList", cn);
            cm.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(cm);
            DataTable dt = new DataTable();
            da.Fill(dt);
            List<TeamLdr> TeamLdrList = new List<TeamLdr>();
            foreach (DataRow dr in dt.Rows)
            {
                TeamLdrList.Add(new TeamLdr
                {
                    ProjectLeader = Convert.ToInt32(dr["EmployeeId"].ToString()),
                    ProjectLeaderName = dr["EmpName"].ToString()
                });
            }
            return TeamLdrList;
        }
        public List<ProjectMgr> GetProjectMgrList()
        {
            SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString());
            SqlCommand cm = new SqlCommand("GetProjectMgrList", cn);
            cm.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(cm);
            DataTable dt = new DataTable();
            da.Fill(dt);
            List<ProjectMgr> projectList = new List<ProjectMgr>();
            foreach (DataRow dr in dt.Rows)
            {
                projectList.Add(new ProjectMgr
                {
                    ProjectManager = Convert.ToInt32(dr["EmployeeId"].ToString()),
                    ProjectManagerName = dr["EmpName"].ToString()
                });
            }

            return projectList;
        }

        public Project GetProjectEdit(int ProjectId)
        {
            SqlCommand cm = new SqlCommand("GetProjectEdit", cn);
            cm.Parameters.AddWithValue("@Projectid", ProjectId);
            cm.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(cm);
            DataTable dt = new DataTable();
            da.Fill(dt);
            Project projectList = new Project
                {
                    ProjectId = Convert.ToInt32(dt.Rows[0]["ProjectId"].ToString()),
                    ProjectLeader = Convert.ToInt32(dt.Rows[0]["ProjectLeader"].ToString()),
                    ProjectName = dt.Rows[0]["ProjectName"].ToString(),
                    ProjectType = Convert.ToInt32(dt.Rows[0]["ProjectType"].ToString()),
                    ProjectTypeName = dt.Rows[0]["ProjectTypeName"].ToString(),
                    ClientId = Convert.ToInt32(dt.Rows[0]["ClientId"].ToString()),
                    ClientName = dt.Rows[0]["ClientName"].ToString(),
                    ClientConcernPerson = dt.Rows[0]["ClientConcernPerson"].ToString(),
                    ContactNo = dt.Rows[0]["ContactNo"].ToString(),
                    GivenDate = dt.Rows[0]["GivenDate"].ToString(),
                    DeliveryDate = dt.Rows[0]["DeliveryDate"].ToString(),
                    ProjectManager = Convert.ToInt32(dt.Rows[0]["ProjectManager"].ToString()),
                    ProjectManagerName = dt.Rows[0]["ProjectManagerName"].ToString(),
                    ProjectLeaderName = dt.Rows[0]["ProjectLeaderName"].ToString(),
                    //ProjectMgrList = GetProjectMgrList(),
                    //TeamLdrList = GetTeamLdrList()
                };            
            return projectList;
        }
        public List<Project> GetProjectListByFilter(string projectName, int projectType)
        {
            SqlCommand cm = new SqlCommand("GetProjectListByFilter", cn);
            cm.Parameters.AddWithValue("@ProjectName", projectName);
            cm.Parameters.AddWithValue("@ProjectType", projectType);
            cm.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(cm);
            DataTable dt = new DataTable();
            da.Fill(dt);
            List<Project> projectList = new List<Project>();

            foreach (DataRow dr in dt.Rows)
            {
                projectList.Add(new Project
                {
                    ProjectId = Convert.ToInt32(dr["ProjectId"].ToString()),
                    ProjectLeader = Convert.ToInt32(dr["ProjectLeader"].ToString()),
                    ProjectName = dr["ProjectName"].ToString(),
                    ProjectType = Convert.ToInt32(dr["ProjectType"].ToString()),
                    ProjectTypeName = dr["ProjectTypeName"].ToString(),
                    ClientId = Convert.ToInt32(dr["ClientId"].ToString()),
                    ClientName = dr["ClientName"].ToString(),
                    ClientConcernPerson = dr["ClientConcernPerson"].ToString(),
                    ContactNo = dr["ContactNo"].ToString(),
                    GivenDate = dr["GivenDate"].ToString(),
                    DeliveryDate = dr["DeliveryDate"].ToString(),
                    ProjectManager = Convert.ToInt32(dr["ProjectManager"].ToString()),
                    ProjectManagerName = dr["ProjectManagerName"].ToString(),
                    ProjectLeaderName = dr["ProjectLeaderName"].ToString()
                });

            }
            return projectList;
        }

        public int SaveProject(Project project, int flag)
        {
            if (cn.State == 0)
            {
                cn.Open();
            }

            DataTable dt = new DataTable();
            SqlCommand cm = new SqlCommand("InsertProjectMaster", cn);
            cm.CommandType = CommandType.StoredProcedure;
            cm.Parameters.AddWithValue("@projectid", project.ProjectId);
            cm.Parameters.AddWithValue("@clientid", project.ClientId);
            cm.Parameters.AddWithValue("@projectName", project.ProjectName);
            cm.Parameters.AddWithValue("@projectType", project.ProjectType);
            cm.Parameters.AddWithValue("@ClientConcernPerson", project.ClientConcernPerson);
            cm.Parameters.AddWithValue("@ContactNo", project.ContactNo);
            cm.Parameters.AddWithValue("@GivenDate", project.GivenDate);
            cm.Parameters.AddWithValue("@DeliveryDate", project.DeliveryDate);
            cm.Parameters.AddWithValue("@projectMgr", project.ProjectManager);
            cm.Parameters.AddWithValue("@projectLdr", project.ProjectLeader);
            cm.Parameters.AddWithValue("@flag", flag);
            cm.Parameters.AddWithValue("@retval", 0);
            cm.Parameters["@retval"].Direction = ParameterDirection.InputOutput;
            cm.ExecuteNonQuery();
            int retval = Convert.ToInt32(cm.Parameters["@retval"].Value.ToString());
            return retval;
        }

        public int DeleteProject(int ProjectID)
        {
            if (cn.State == 0)
            {
                cn.Open();
            }

            SqlCommand cm = new SqlCommand("DeleteProject", cn);
            cm.CommandType = CommandType.StoredProcedure;
            cm.Parameters.AddWithValue("@ProjectId", ProjectID);
            cm.Parameters.AddWithValue("@retval", 0);
            cm.Parameters["@retval"].Direction = ParameterDirection.InputOutput;
            cm.ExecuteNonQuery();

            int retval = Convert.ToInt32(cm.Parameters["@retval"].Value.ToString());
            return retval;
        }

      
    }


И Контроллер

public class ProjectController : ApiController
    {
Project p;
 [HttpPost]
        public Project SaveProject(Project project)
        {
             p = new Project();
             int retval = p.SaveProject(project, 1);
            return p;
        }
}


Что я уже пробовал:

Я использовал [From Body] в методе post, но это не сработало

Afzaal Ahmad Zeeshan

На самом деле это [FromBody] будет работать именно так, как вы хотите, но вопрос в том, содержит ли тело полезную нагрузку объекта, которую можно разобрать на тип проекта?

manish.communityhub

Да он содержит точно такой же тип вот мой json:
{"ProjectId":0,"ClientId":1,"ClientName":"","ProjectName":"asdasd","ProjectType":1,"ProjectTypeName":"","ClientConcernPerson":"wqewqe","ContactNo":"231231234324","GivenDate":"01-02-2017","DeliveryDate":"10-06-2017","ProjectManager":32,"ProjectLeader":18,"ProjectManagerName":"","ProjectLeaderName":""}

Afzaal Ahmad Zeeshan

Кроме того, почему у вас есть другой и отдельный объект p в коде?

Что касается этого, то код должен работать. Могу ли я попросить вас использовать Postman для отладки API? Он покажет вам, что происходит под капотом вашего API.

manish.communityhub

Проблема Решена:
На самом деле я не определил общедоступные данные члены класса

0 Ответов