Web API parameter bind dynamically built table values to model?

时间:2016-10-20 18:43:49

标签: c# asp.net-web-api model parameterbinding

Imagine you were creating an online test application. It lets you add multiple choice test questions. So the user clicks "Add new test question" and a dialog comes up. The dialog asks for the question text, a list of possible answers, and the correct answer. So something like this would be the result:

    Which color has the letter "G" in it?
            A.  Blue
            B.  Red
    ---->   C.  Green
            D.  Yellow
            E.  Purple

Each new question would likely have different number of options. So the next question might be:

    Does NYC have 5 boroughs?
    --->    A.  Yes
            B.  No

I've created a dialog that allows the user to dynamically build those questions (add answers, designate the correct one, etc.) inside a form. Is there anyway to create a model and a Web API that would seamlessly parameter bind that structure on form submission? I was thinking something crazy like if my form had a table in it that I could somehow bind that to an array in my model? Probably doesn't work like that but looking for a creative idea.

1 个答案:

答案 0 :(得分:0)

A model could look something like this

public class Question {
    public string Text { get; set;}
    public IList<Answer> Answers { get; set;}
}

public class Answer {
    public string Label { get; set;}
    public string Text { get; set;}
    public bool IsCorrect { get; set;}
}

An api endpoint would take a collection of these to form a test.

public class Test {
    public IList<Question> Questions { get; set; }
}

public class TestController : ApiController {
    [HttpPost]
    public IHttpActionResult Create(Test test) { ... }
}