Ignore class attributes using Datamember C#

Asked

Viewed 23 times

0

I’m trying to return a json from a controller by ignoring some of the fields in it.

Controller:

    [HttpGet]
    public IActionResult Get()
    {
        var result = _service.Generate();

        if (result == null)
            BadRequest();

        return Json(result);
    }

My service returns a view model:

[DataContract]
public class MenuViewMapping
{
    public MenuViewMapping()
    {
        Children = new List<MenuViewMapping>();
    }
    [DataMember]
    public string Id { get; set; }
    [DataMember]
    public string Title { get; set; }
    public string Permissions { get; set; }
    [DataMember]
    public string Url { get; set; }
    public bool VisibleWithNoChild { get; set; }
    [DataMember]
    public List<MenuViewMapping> Children { get; set; }
}

I’m trying to make the fields Permissions and VisibleWithNoChild are ignored when returning Json. My service basically reads a json and assembles the objects to mount a dynamic menu.

It arrives in the controller with all the information, but does not ignore the above attributes.

  • 2

    From a glance at the answer I gave in the question above, you can use the attribute JsonIgnore.

  • It worked, I use the JsonIgnore and made the return as Ok(result), I only had to do a serialization before returning the result. It worked! Thanks :D

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.