S
S
Sneiksus2019-08-08 17:53:04
JavaScript
Sneiksus, 2019-08-08 17:53:04

What should be the receiving type in the controller?

js script sends post request to asp.net controller
$.post("/Home/Add" , {"A":"a" , "B":"b"});

[HttpPost]
   public void Add(/*.....*/) {}


What should be the type of the receiving parameter in the Add function in order to accept an array from javascript?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
ivanresh, 2019-08-08
@Sneiksus

It must be a class with the same properties as you are sending, and the [FromBody] attribute must be added:

public class Word
{
public string A { get; set; }
public string B { get; set; }
}

[HttpPost]
public void Add([FromBody]Word word)
{

}

Sending an object is more difficult:
public class TestClass
{
      public int Prop { get; set; }
}

public class Word
{
public TestClass A{ get; set; }
public string B { get; set; }
}

[HttpPost]
public void Add([FromBody]Word word)
{

}

Array:
public class Word
{
       public string A{ get; set; }
}

[HttpPost]
public void Add([FromBody]IEnumerable<Word> words)
{

}

Use different naming properties on behalf of:
public class Word
{
       [JsonProperty("OtherName")]
       public string A{ get; set; }
}

[HttpPost]
public void Add([FromBody]IEnumerable<Word> words)
{

}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question