locked
Hi is there any way to use a view model to send data via a web api? RRS feed

  • Question

  • User2130491911 posted

    Hello All,

    I have a web api program that feeds data into a phone application... the problem is that I am sending data from a table im the database (sql)

    It works fine but I notice in the phone application that my two date fields are not formatted like I need them..

    They come over to the phone application formated like theis  2018-12-12T00:00:00

    and the other comes over  2018-12-12T20:30:00

    For one field I want it to have time and for the other I just want date.

    I was hoping I could change this is the api program and not have to deal with the phone application as I don't know how to change the formats there.

    So in the view model I made 

    the field uses this:

    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] and this  [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy HH:ss}")]


    But When I try to pass a view model I get nothing when I call the api program

    There is my web api program code

            public IHttpActionResult GetTheInfo()
            {
                The_INFO_VIEWMODEL TheInfo = new The_INFO_VIEWMODEL();
                return Ok(TheInfo);
    
            }

    my out put frim the web api is :

    <THE_INFO_VIEWMODEL xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/THE_WEB_API.Models"/>

    Thursday, December 20, 2018 10:08 PM

Answers

  • User36583972 posted

    Hi AppDev01,

    They come over to the phone application formated like theis  2018-12-12T00:00:00

    and the other comes over  2018-12-12T20:30:00

    For one field I want it to have time and for the other I just want date.

    I was hoping I could change this is the api program and not have to deal with the phone application as I don't know how to change the formats there.

    So in the view model I made 

    the field uses this:

    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] and this  [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy HH:ss}")]

    You want to get the different datetime format for each field. You can consider the following method.

    Model:

      [DataContract]
        public class Team2
        {
            [DataMember]
            public int id { get; set; }
    
            [DataMember]
            public string Name { get; set; }
    
            public DateTime DateTime1 { get; set; }
    
            [DataMember]
            public string DateTimeOne
            {
                get { return this.DateTime1.ToString("MM/dd/yyyy"); }
                set { this.DateTime1 = DateTime.Parse(value); }
            }
    
            public DateTime DateTime2 { get; set; }
    
            [DataMember]
            public string DateTimeTwo
            {
                get { return this.DateTime2.ToString("MM/dd/yyyy HH:mm:ss"); }
                set { this.DateTime2 = DateTime.Parse(value); }
            }
        }

    XML Media-Type Formatter
    https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/json-and-xml-serialization#xml-media-type-formatter

    Best Regards,

    Yong Lu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, December 21, 2018 6:55 AM

All replies

  • User36583972 posted

    Hi AppDev01,

    They come over to the phone application formated like theis  2018-12-12T00:00:00

    and the other comes over  2018-12-12T20:30:00

    For one field I want it to have time and for the other I just want date.

    I was hoping I could change this is the api program and not have to deal with the phone application as I don't know how to change the formats there.

    So in the view model I made 

    the field uses this:

    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] and this  [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy HH:ss}")]

    You want to get the different datetime format for each field. You can consider the following method.

    Model:

      [DataContract]
        public class Team2
        {
            [DataMember]
            public int id { get; set; }
    
            [DataMember]
            public string Name { get; set; }
    
            public DateTime DateTime1 { get; set; }
    
            [DataMember]
            public string DateTimeOne
            {
                get { return this.DateTime1.ToString("MM/dd/yyyy"); }
                set { this.DateTime1 = DateTime.Parse(value); }
            }
    
            public DateTime DateTime2 { get; set; }
    
            [DataMember]
            public string DateTimeTwo
            {
                get { return this.DateTime2.ToString("MM/dd/yyyy HH:mm:ss"); }
                set { this.DateTime2 = DateTime.Parse(value); }
            }
        }

    XML Media-Type Formatter
    https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/json-and-xml-serialization#xml-media-type-formatter

    Best Regards,

    Yong Lu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, December 21, 2018 6:55 AM
  • User2130491911 posted

    Ahhh ok... I did not know you could do that! Thank you very much!

    Friday, December 21, 2018 3:49 PM
  • User2130491911 posted

    Is this datacontract something different than the model? 

    Am I doing this in the Api program or am I doing this in the application using the Api?  

    Just seeking some clarity...Thanks!

    Friday, December 21, 2018 4:20 PM
  • User475983607 posted

    Is this datacontract something different than the model? 

    Am I doing this in the Api program or am I doing this in the application using the Api?  

    Just seeking some clarity...Thanks!

    The attributes control serialization.  The link in Yohann Lu's post explains the details.

    Friday, December 21, 2018 6:44 PM
  • User2130491911 posted

    Hi yeah I tried following it and putting the information where I thought it should go... but when I try to use datetime.. it fails... I am using xamarin and I asked them and they said this was a more a c# issues... I should not be this hard to formate a date...

    So is there an easier way like doing this at the api level where it makes better since to me.. can I do data annotation in a partial class or something in the web api?

    I have a example of there when i was trying to understand view models which I still can't wrap my brain around as there is no way to populate them that I can tell...

    but is there a way to just go into a partial class and make this time date data format in the way I want si when it sends it to the phone app its right?

    One thing I could not tell from the example was where this code should go... if I put it in the model for the table... that gets over written if the table gets updated correct?

    Saturday, December 22, 2018 12:18 AM
  • User2130491911 posted

    The attributes control serialization

    I am not sure what is meant by that.. is there a non technical way to describe this?

    Sorry I read though the site and its a bit over my head as this is the first time every seeing this.

    Saturday, December 22, 2018 12:20 AM
  • User475983607 posted

    but is there a way to just go into a partial class and make this time date data format in the way I want si when it sends it to the phone app its right?

    In C# a DateTime is a type, a struct to be exact.  A date format is a string that represents a date which is driven by local and culture.  A DateTime type can be converted to whatever format you like as illustrated in the previous post.  See the docs for more information.

    https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings

    https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings

    I am not sure what is meant by that.. is there a non technical way to describe this?

    Serialization referents to taking data stored in memory and sending the data down a wire one byte at a time; serialized.  The sender and receiver must agree on the format.  The attributes provide a mechanism to define the serialized format.

    Programming is a technical field and requires understanding technical concepts.

    Saturday, December 22, 2018 5:06 AM
  • User2130491911 posted

    thanks for the info on the meaning...

    So my api is working but I dont know how to format that date value.

    I am trying to understand where I would make these edits so that I can change the date formating as it relates to sending that data...

    In the api I built I am using EF and sending the table... EF has a model... do I make these changes in that model?

    and if I do make the changes to the date there using that datacontract thing... will it get over witten if I have to update that

    model? Or do you do that data contract thing in som other file.. that is whats not clear.

    AppDev01

    but is there a way to just go into a partial class and make this time date data format in the way I want si when it sends it to the phone app its right?

    In C# a DateTime is a type, a struct to be exact.  A date format is a string that represents a date which is driven by local and culture.  A DateTime type can be converted to whatever format you like as illustrated in the previous post.  See the docs for more information.

    https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings

    https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings

    AppDev01

    I am not sure what is meant by that.. is there a non technical way to describe this?

    Serialization referents to taking data stored in memory and sending the data down a wire one byte at a time; serialized.  The sender and receiver must agree on the format.  The attributes provide a mechanism to define the serialized format.

    Programming is a technical field and requires understanding technical concepts.

    Saturday, December 22, 2018 1:58 PM
  • User475983607 posted

    The concept is very simple.  Services like Web API transfer models from the [server memory to client memory] and [client memory to server memory] over a network connection.  Most of the heavy lifting is handled by the framework.

    Web API is one endpoint and the client calling Web API is the other endpoint.  In between the endpoints is a wire.  The Web API endpoint takes the return type (the model) from memory and converts it into a format that can travel over the wire; a serialized stream. The client receives the stream from the wire.  Converts the serialized stream back into a .NET type which puts the model in the client's memory.

    Basically, you are fabricating problems where no problems exists.  First, you are confusing the string representation of a date, the serialized format) with the DateTime type.  Second, you are also looking at the serialized stream rather than focusing on deserializing the stream first.  Once you have the .NET type - the Datetime - in memory, you can format the DateTime anyway like until the cows come home.  See the DateTime format links in my previous posts.

    The HttpClient docs from the learn link illustrate with examples how to deserialize a stream.  It's like one or two lines - very simple.  

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client

    Saturday, December 22, 2018 2:51 PM
  • User2130491911 posted

    Hi thanks again.. i read through this as well and sadly this is even more confusing to me as I am not seeing anything related to changing the date format. The issue is that the sql database is sending a datetime value. The phone app is getting the data just fine.. its displaying the data fine..the date is just not formatted like I wanted it.

    The people over a xamarin are saying this is a c# issue as all the things they said try fails..

    The user here on this site pointed me to something called a data contract but did not say where it should be applied. Reading about the data contract it is not clear how it is used or where it goes. Yeah so for 5 Days now I have been trying to get a date formatted.. I have read lots of instructions and asked many questions on 3 forums now.

    Clearly i cant figure  this one out.. so i will just write this up as a known bug in my program. and in the users guide we can explain this away.. thought i would try to fix it before I deployed the app... but I cant fix not going to worry about it . I know when Im beaten lol.

    Thanks anyway.


    I will just mark this issue down as a known bug in the program... we can also train our users to deal the mis formatted date...

    This will be just for display in the phone app... I was hoping this was going to be an easy fix but clearly its not...

    Sunday, December 23, 2018 2:15 AM
  • User475983607 posted

    AppDev01

    i read through this as well and sadly this is even more confusing to me as I am not seeing anything related to changing the date format.

    Sadly, you're making up a problem when there's no problem.  You've been given a working solution. 

            public DateTime DateTime1 { get; set; }
    
            [DataMember]
            public string DateTimeOne
            {
                get { return this.DateTime1.ToString("MM/dd/yyyy"); }
                set { this.DateTime1 = DateTime.Parse(value); }
            }

    All I tried to do is explain why the solution works and where the holes are in your understanding in the even you wanted to learn how serialization works.

    Sunday, December 23, 2018 12:35 PM
  • User2130491911 posted

    Hi Yes I may not be clear... I did learn a good  bit from what you are posting...as well as the examples... but I think what is being missed and its most likely my fault... is that no one seems to be able to share where the code examples go in the program...

    In all the reading it never says how to integrate whats being showed. I get what it is the code is doing... but I don't understand where the datacontract code goes in the program...

    Does it go in the api code?

    Does it go in the Phone code?

    I tried the code in the api application... nothing changes so I take it out

    I try it In the model for the phone... using data contract examples. THe phone app stop working as it seems to fail at the get api.. it gives no errors..

    it just stops displaying the data... I take out the changes... the phone application work...

    Again... If these changes go in the Api and I used EF to import the table from my database first situation... this has a model already that was auto generated ....do I change it there? Which seems odd i thats the case be cause if that model gets updated.. I lose my changes..which makes me think I do it in the phone app.. but people at the xamarin site say its a c# issues... if i do it in the phone where I have tried to do it.. it does not work.. nothing is changing....

    So you have to see why I am ready to just write this off as a bug...

    This may be easy for experts like you guys... to me it is not because the instuction are never clear on these microsoft sites... they do not seem to account for how things

    happen in the real world programing  in my opinion... your skill set may allow you to decepher the cepher.. I dont have that skillset.

    Easy for you..a horror show for me... some much time wasted so may people sharing opinions that this is easy... and what ever else...

    So at this point... i have to accept the fact I cant solve this issue. It is beyond what I know. So I guess  I dont care any more.. and it will just have]

    to stay the way it is..

    At some point another programmer will follow and will just have to fix this if the client finds it to be an bug they cant live with it.

    Once its turned over to the client... its not longer my problem anymore... and since its just a date format.. its not all that critical and can be explained away as a bug.

    And in the user guide it can be explain what the format means..

    Thank you for trying...

    Sunday, December 23, 2018 1:43 PM
  • User475983607 posted

    In all the reading it never says how to integrate whats being showed. I get what it is the code is doing... but I don't understand where the datacontract code goes in the program...

    Does it go in the api code?

    Does it go in the Phone code?

    The [DataContract] attributes decorate the model properties as shown above. 

    If in the Api and I used EF to import the table from my database first situation... this has a model that was auto generated ....do I change it there? Which seems odd i thats the case be cause if that model gets updated.. I lose my changes..

    Entities are an in-memory representation of the database tables.  You are not supposed to return Entities directly.  The serialization process will populate all the navigation properties which is generally unwanted especially if there's a lot of records..  The standard approach is populating a model from the Entities and returning the model.  We've been down this path in your other threads many times.

    So you have to see why I am ready to just write this off as a bug...

    This may be easy for experts like you guys... to me it is not because the instuction are never clear on these microsoft sites... they do seem to account for how things

    happen in the real world in my opinion... your skill set may allow you to decepher the cepher.. I dont have that skillset.

    Easy for you..a horror show for me... so at this point I dont care any more as this is beyond my skill set. At some point another programmer will just have to fix this if the client finds it to be an bug they cant live with it.

    Once its turned over to the client... its not longer my problem anymore... and since its just a date format.. its not all that critical and can be explained away as a bug.

    Thank you for trying...

    It took me a time and effort to learn these concepts.  I'm sure many of the forum members spent considerable time learning as well   The best we can do is pass our knowledge.  It's up to you to take the knowledge and do something with it.  If you want to spin the date format as a bug rather than learning, cool.

    Sunday, December 23, 2018 2:16 PM
  • User2130491911 posted

    Hi don't think I don't appricate the attempt to help... I really do.

    YOu can type what ever you want about what you think im doing as it relates to learning...

    not every one may be as smart as you...not everyone grasp what you know.. not everyone learns the same way.\

    Just because you type something does not  mean its clear to a reader.. Just saying...

    The program has models.. which one? the instruction does not make that clear.. the microsoft site which I have a hard time

    translating is hard to understand as none of their examples make any sense to me. They never have as they are two general.

    So for me this issue is a tough one to figure out...might be easy for you... but not for me...  and I am not ashamed to admit that.

    But what it does not mean is that I am not learning from failures. It does not mean that I don't learn from my research or answer by people trying to help/

    So please dont you dare try to charaterize my methods of learning.

    Its pretty simple. I don;t know the solution... it is that and nothing more.

    It does not matter if you know the solution. But as the asker... I have to translate what you are trying to share.

    I am trying to find the solution. Sadly I don't know how to translate all the guidance from you and others.

    There gaps... there are some missing details. If we were face to face I might be able to ask a follow up to get a more clear answer.

    All I can do is take what you suggest and look up on other sites to try to piece together your advice with someones elses advice and try it. And if it does not work, I try to use the key phases in the suggestion to seach again for a solution.

    THats not discarding your knowledge that you share... its taking what you have shared and trying to find a better way to ask a question or find a clearer solutions.

    Some of  the items you share are a bit too technical for me to understand. So I take what you share or ask for clearity to translate it to a less technical explaination. I think some times these expert communities have some unrealistic expectations on what they think people other than people like them should know. LOL.  And if they don;t know it they have people attempt to label them kind of like you may be doing as we have a history of interacting.

    Its all okay.. You all speak the same technical language. I take what is shared by the community and try to find a real world example to help my solve the problem. On this one I am out of luck. I'm okay with that.

    7days of research has left me in the same space. I know I am not the only programmer to have faced this problem.. But now its going to have to be left for a future developer as I can't find the solution. Thats not a rejection of learning.. thats accepting the facts. I can't fix this. Someone with more knowledge will have to. Maybe someone with smarts like you will find a solution. This is the real world mate.

    Not the special world of fourms where everyone is a super guru expert.

    As always I do think you and all others for the help...

    mgebhard

    AppDev01

    In all the reading it never says how to integrate whats being showed. I get what it is the code is doing... but I don't understand where the datacontract code goes in the program...

    Does it go in the api code?

    Does it go in the Phone code?

    The [DataContract] attributes decorate the model properties as shown above. 

    AppDev01

    If in the Api and I used EF to import the table from my database first situation... this has a model that was auto generated ....do I change it there? Which seems odd i thats the case be cause if that model gets updated.. I lose my changes..

    Entities are an in-memory representation of the database tables.  You are not supposed to return Entities directly.  The serialization process will populate all the navigation properties which is generally unwanted especially if there's a lot of records..  The standard approach is populating a model from the Entities and returning the model.  We've been down this path in your other threads many times.

    AppDev01

    So you have to see why I am ready to just write this off as a bug...

    This may be easy for experts like you guys... to me it is not because the instuction are never clear on these microsoft sites... they do seem to account for how things

    happen in the real world in my opinion... your skill set may allow you to decepher the cepher.. I dont have that skillset.

    Easy for you..a horror show for me... so at this point I dont care any more as this is beyond my skill set. At some point another programmer will just have to fix this if the client finds it to be an bug they cant live with it.

    Once its turned over to the client... its not longer my problem anymore... and since its just a date format.. its not all that critical and can be explained away as a bug.

    Thank you for trying...

    It took me a time and effort to learn these concepts.  I'm sure many of the forum members spent considerable time learning as well   The best we can do is pass our knowledge.  It's up to you to take the knowledge and do something with it.  If you want to spin the date format as a bug rather than learning, cool.

    Monday, December 24, 2018 12:50 AM
  • User2130491911 posted

    Here is an example of what I am on about...

    Here is a full example as I did a internet search for Datacontract...

    The write leave out the key information on how one would use this with a datbase first situation.

    https://www.c-sharpcorner.com/uploadfile/anup1252000/basics-of-datacontract/

    My program has a model that was generated by the wizard when I updated it from a database that already exist.

    Now where would I put this data contract item???

    In all the examples I have read on this ... even the suggestions here... no one seems to cover that part...

    At this point its pointless as I am done with the  project.. but It would be nice to know for the future... where I would use

    a data contract option if I ever have to do this again. (which I hope is never as dates are very hard to work with lol)

    Monday, December 24, 2018 2:00 AM