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.
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) { ... }
}
Related
I want to accept different model type from body based on query param value.
Example:
[HttpGet]
[Route("GetSystemdetails")]
public string Getdeatils([FromBody] SystemDetail sysdetails, string type)
{
//some code here
string details = getdetails(sysdetails);
}
// abc model
public class abc
{
public int UserID { get; set; }
public string Email { get; set; }
}
//xyz model
public class xyz
{
public int xyzid { get; set; }
public string systemval { get; set; }
public string snum { get; set; }
}
type abc and xyz will have it's own model. So based on type I receive in query param I wanted to pick the model and proceed.
Sample url:
localhost/GetSystemdetails/type=abc
localhost/GetSystemdetails/type=xyz
I thought of creating a new model SystemDetail which holds these two models(xyz and abc) and based on system pick them.
I wanted to know what are possible ways to achieve this kind of requirements without creating multiple methods in controller(I don't want to change the format of the URL).
That's not something that's supported out of the box. Your linked solution is probably the closest you'll get to that.
ASP.NET Core is not supposed to take values of the parameters into account when routing, except for validation.
There are several possible ways to do so
Having multiple model objects
As in the link you provided, you can declare multiple model objects. The site has given the example of
public class PostUserGCM
{
public User User { get; set; }
public GCM GCM { get; set; }
}
but you can use your own examples.
Base model
Your models can inherit from some base model. If you only need a single model at a time and they share some similarities, then you could just create a base model which the other two are inheriting from, be agnostic at implementation time and your use cases will mainly differ on instantiation inside the controller, while some service methods could handle other differences.
I am working on a service oriented architecture. I have 3 tables Meeting, Stakeholder and MeetingStakeholder (a junction table).
A simple representation of POCO classes for all 3 tables:
public class Meeting
{
public int Id { get; set; }
public IList<MeetingStakeholder> MeetingStakeholders { get; set; }
}
public class Stakeholder
{
public int Id { get; set; }
}
public class MeetingStakeholder
{
public int Id { get; set; }
public int MeetingId { get; set; }
public Meeting Meeting { get; set; }
public int StakeholderId { get; set; }
public Stakeholder Stakeholder { get; set; }
}
A simple representation of Meeting Dto:
public class MeetingDto
{
public int Id { get; set; }
public IList<int> StakeholderIds { get; set; }
}
In PUT action,
PUT: api/meetings/1
First I removes all existing records from MeetingStakeholder (junction table) then prepares new List<MeetingStakeholder> meetingStakeholders using meetingDto.StakeholderIds and create it.
{
List<MeetingStakeholder> existingMeetingStakeholders = _unitOfWork.MeetingStakeholderRepository.Where(x=> x.MeetingId == meetingDto.Id);
_unitOfWork.MeetingStakeholderRepository.RemoveRange(existingMeetingStakeholders);
List<MeetingStakeholder> meetingStakeholders = ... ;
_unitOfWork.MeetingRepository.Update(meeting);
_unitOfWork.MeetingStakeholderRepository.CreateRange(meetingStakeholders);
_unitOfWork.SaveChanges();
return OK(meetingDto);
}
Everything is fine to me. But my architect told me that i am doing wrong thing.
He said, in PUT action (according to SRP) I should not be removing and re-creating MeetingStakeholder records, I should be responsible for updating meeting object only.
According to him, MeetingStakeholderIds (array of integers) should be send in request body to these routes.
For assigning new stakeholders to meeting.
POST: api/meetings/1/stakeholders
For removing existing stakeholders from meeting.
Delete: api/meetings/1/stakeholders
But the problem is, In meeting edit screen my front-end developer uses multi-select for Stakeholders. He will need to maintain two Arrays of integers.
First Array for those stakeholders Ids which end-user unselect from multi-select.
Second Array for new newly selected stakeholders Ids.
Then he will send these two arrays to their respective routes as I mentioned above.
If my architect is right then I have no problem but how should my front-end developer handle stakeholders selection in edit screen?
One thing I want to clarify that my junction table is very simple, it does not contain additional columns other than MeetingId and StakeholderId ( a very basic junction). So in this scenario, does it make sense to create separate POST/DELETE actions on "api/meetings/1/stakeholders" that receives StakeholderIds (list of integers) instead of receiving StakeholderIds directly in MeetingDto??
First of all, if I am not mistaken:
you have a resource: "Meeting";
you want to update the said resource (using HTTP/PUT).
So updating a meeting by requesting a PUT on "/api/meetings/:id" seems fairly simple, concise, direct and clear. All good traits for designing a good interface. And it still respects the Single Responsibility Principle: You are updating a resource"
Nonetheless, I also agree with you architect in providing, in addition to the previous method, POST/Delete actions on "api/meetings/1/stakeholders" if the requisites justify so. We should be pragmatic at some level not to overengineer something that isn't required to.
Now if your architect just said that because of HOW IT IS PERSISTED, then he is wrong. Interfaces should be clear to the end user (frontend today, another service or app tomorrow ...), but most importantly, in this case, ignorant of its persistence or any implementation for that matter.
Your api should focus on your domain and your business rules, not on how you store the information.
This is just my view. If someone does not agree with me I would like to be called out and so both could grow and learn together.
:) Hope I Could be of some help. Cheers
I am a newbie and creating a website where you can create your own custom quizes. Ive made a database that stores a class object mytests that consists of a name, and a list of questions parameter.
public class MyTests
{
public int ID { get; set; }
public string name { get; set; }
public string description { get; set; }
public List<MyQuestions> AllTestQuestions;
}
//using this object for questions
public class MyQuestions
{
public string QuestionDescription { get; set; }
public string MultipleChoiceCorrect { get; set; }
public string MultipleChoiceB { get; set; }
public string MultipleChoiceC { get; set; }
public string MultipleChoiceD { get; set; }
public string Answerexplanation { get; set; }
}
I'm using the default database code generated by visual studio. I have no problem adding this test object(mytest) to the database, but what I want to do is that on the edit.cshtml view I want to be able to add elements to the question list before returning the object to the database saved.
The problem is I don't know how to edit the model object from the view, or if this is even possible. I could maybe get it to work through a redirect? but I thought that adding the elements directly from the view would be easier. Is it possible to modify the model.object inside a view from the view (putting security concerns aside)?
For example model.title = something;
or
model.list.add()
Is anything like this possible?
If this question is not clear please let me know and I will try to clarify in the comments.
Yes, it is possible to edit the model from within the view.
From within your .cshtml file specify the view model using the #model declaration, then edit the model like so:
#model Namespace.For.MyTests
#Model.name = "Hello World";
<p>#Model.name</p>
Whilst this would work, it's not really what the view is for so I wouldn't recommend it.
The view is about presenting your data, not mutating it - that should be done in the controller, or domain layer. As soon as the user leaves the page then your changes will be lost due to the stateless nature of the web (.NET MVC passes data to the view from the controller, then ends the request).
This should be done at the controller level. You could do it on a view but it's not what the view is for.
Your issue is that if the page is refreshed you will lose you content, so if you do anticipate on the page refreshing you will need a way in which to temporarily hold the information before it being saved.
On a side note, I'd also consider renaming your classes "MyTests" to "MyTest" (singular) and "MyQuestions" to "MyQuestion"... it's just good practice because then you'd have a List of singleton "MyQuestion" in a "MyTest". EntityFramework Codefirst will pluralise the names when the database is created/update.
I am developing a learning management system with asp.net c#
now i want to make a structure for generating university forms , but these forms may change in future or need new forms , i want make a structure for admin of website to generate custom forms without coding, admin only add the name of feilds and type of that ( its text box or checkbox and ... ) , then it should be a printable from , also admin can add explanation in diffrent part of the form...
i dont know how should i do this ?
is there any API or some idea ?
You could make some clases for your form controls like: InputBox, TextBox, CheckBox, RadioButton. Then a form class could contain lists of your input controls.
class FormInputControl
{
public string Description { get; set; } //Every form input has a description like User, link, what you want that form input control instance to describe
public abstract object Value { get; set; }
}
class InputBox : FormInputControl
{
public string Text { get; set; }
public overwrite object Value
{
get { return Text; }
set { Text = value as string; }
}
}
class Form
{
public IList<FormInputControls> { get; set; }
}
I'm looking for a way to achieve the following in MVC 3.
Let's say I have a page with one question. On a post, I would like to bind the following ViewModel:
public class QuestionElementViewModel
{
public int QuestionId { get; set; }
public string Name { get ; set; }
public string Question { get; set; }
public string Feedback { get; set; }
}
This can easily be done like this (if I use the correct names in the View):
[HttpPost]
public ActionResult Index(QuestionElementViewModel pm)
{
//Do something
}
Now I have multiple questions on my page. Using the technique explained here: http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx I can also make this quite easy:
[HttpPost]
public ActionResult Index(QuestionElementViewModel[] pm)
{
//Do Something
}
But lets say I don't have only questions, but different elements on my page and these elements can vary. Would it be somehow possible to achieve something like this:
[HttpPost]
public ActionResult Index(IElementViewModel[] pm)
{
//Do Something
}
where every ViewModel that implements this interface is automatically bound?
I've tried this code and it results in an error: Cannot create instance of an interface, which sounds pretty obvious.
I think i should create a custom model-binder, but I'm not very familiar with that and I don't want to step away from the standard MVC-framework too much..
You will need a custom model binder for this scenario because you are using an interface and the default model binder wouldn't know which implementation to instantiate. So one possible technique is to use a hidden field containing the concrete type for each element. Here's an example that might put you on the right track.