Get value from Entity Framework for Dropdown List and Return selected value in MVC - entity-framework

Assuming i got a table called Countries and using Entity Framework, i want to know how could i populate the available countries (listed in the table countries) to view as drop down list and return the value to HTTPPost Controller
i got
public ActionResult SignUp()
i think the populate code should be here but i not sure
how to retrieve from entity framework and populate into view
and
[httpPost]
public ActionResult SignUp()
i want to read the user selected value and i think is
int value = form["DropDownListName"].SelectedIndex + 1;
can anyone please guide me on this with some hint or example , please ? Thx a lot =D

To be honest, you're not really working in an MVC pattern here. Don't put UI construction logic in your constructor.
Rather, expose the ID that you want to bind to the list via a model that you pass to a View() method in your constructor.
In your view, use the name of that property as the Name of a Drop-down and create a helper class to generate the list of values.
I'd give you a more specific example, but I'm in the cinema with my iPad, so a bit stuck for access to Visual Studio at the moment!

Related

Thymeleaf form with multiple objects of the same class

Simple problem but can't find a solution: I have a Thymeleaf form used to add a new object, say of a Book class. It works perfectly well and I only need that particular form for adding new objects, not editing the existing ones. The question is: how can I put several objects of the Book class in the same single form? So, purely for convenience, instead of filling form for a single book and clicking Send you can fill form for several books at once and only then click Send, have them all inserted into the database (in whatever order) and also have the option to fill the form partially (e.g. the form has room for 5 books but it will also accept 1, 2, 3 or 4 and you can leave the rest blank).
Edit: I've tried passing a list of object to the Thymeleaf template with the form bound to the whole list and iteration inside, but Thymeleaf throws BingingResultError upon rendering it.
You need to use a wrapper object to realize what you want.
Something like:
public class BooksCreationDto {
private List<Book> books;
// default and parameterized constructor
public void addBook(Book book) {
this.books.add(book);
}
// getter and setter
}
Then you need to pass this object as a model attribute in your controller:
BooksCreationDto booksForm = new BooksCreationDto();
model.addAttribute("form", booksForm);
bind fields using index property
th:field="*{books[__${itemStat.index}__].title}"
and get back the result with
#ModelAttribute BooksCreationDto form
in your controller.
For a complete and detailled explaination visit: https://www.baeldung.com/thymeleaf-list

Lightswitch HTML Client, Set Default Value of List Picker

Lightswitch renders my navigation property as a list picker, but I can't figure out how to set a default value on it. There must be a simple way to do it. I've scoured the net, and all the suggestions look hopelessly kludgy. Is there a good comprehensive tutorial out there for Lightswitch? The most common tasks like setting the default value on a dropdown are ridiculously hard to figure out.
Here's how I did it.
myapp.Address.created = function (entity) {
myapp.activeDataWorkspace.MailListData.CountryRegion_LUs.filter("CountryRegionCode eq 'US'").execute().then(function (result) {
entity.CountryRegion_LU = result.results[0];
});
}
You want to write a handler for the created Javascript event for the parent entity. I'm binding CountryRegion_LUs, which are in the Address entity, so I am binding to the created event of the Address entity, not the CountryRegion_LUs entity. "MailListData" is the name of my database. I'm using an OData query to pull out the CountryRegion_LU that has a CountryRegionCode of "US." I could have simply used "load()" instead of .filter("CountryRegionCode eq 'US'").execute() to load all the records, and then picked the member of the result-set I wanted, say results.result[221], but then I'd be bringing all the data over and filtering client-side.
refer to this post of which I asked myself, there is a detailed answer on the problem you have above: it explains how to set your modal picker/details picker with a default value
Lightswitch HTML Client - set modal picker value when screen created
any questions feel free to ask

Use DataAnnotations to force a DropDownList populated from my model

Is there a way use DataAnnotations to tell Razor to render a DropDownList and populate the choices from a specific field in a specific entity?
Specifically I am capturing a "Calendar Year" property in my View and would like it to be a DropDownList. I am doing this currently by passing the years into my view via the ViewBag and then calling "DropDownListFor". I was hoping for a way to define it in my ViewModel and them simply call "EditorFor".
Thanks!
I can't find a way to do it with a DataAnnotation, but you don't need to use the ViewBag, you could pass the values in, like this:
#Html.ListBoxFor(m => m.SelectedFoos, Model.AllFoos.Select(f => new SelectListItem { Text = f.Name, Value = f.ID }))
(Note: This uses ListBox, taken from an answer here, but should be similar for DropDownList).

ValidationMessageFor returns no information when calling modelState.AddModelStateError

I created a class that implements the IModelBinder interface. Within a method of that class I basically retrieve some values and try to validate them. If the validation fails, I add update the model state with necessary information like below:
DateTime mydate;
if (!DateTime.TryParse(convValue,out mydate))
{
bindingContext.ModelState.AddModelError("Date", "Date was crap");
}
The problem is that Html.ValidationMessageFor(m => m.Model) returns no value. I looked at the MVC source code and found out that a proper key with id "Date" can't be found in the ModelState dictionary.
Why is that ? The controller that returns the view have access to the model state and can enumerate over ModelState.Errors
Thanks,
Thomas
Is "Date" the name of the property you are validating?
The first parameter of ModelState.AddModelError should either be the name of the property you want the validation message to display for, or left as string.Empty if you only want the error to display in in the validation summary.
If you want to display an error message that isn't tied to a specific property of your viewmodel, you could call <%: Html.ValidationMessage("Date") %> in your view to display that particular message if it has been set.
Edit: just realised how old this question is. Ah well, might come in handy anyway...

Pass a variable to a Symfony Form

I am building a web application using Symfony 1.4 and Doctrine for a school and I want to make a very simple form to add a course to a student.
The main problem I have is that in the drop down list I only want to show the courses in which the student is currently not enrolled.
I already have a function in the model (in Student.class.php) which returns all the courses in which the student is not enrolled but the problem is I don't know how to pass the student to the configure() of the form. I have tried several options like passing it with the constructor of the form to a global variable or a special set method but none of them have worked.
Is there any form to pass the student to the configure() method?
Thanks!
This should work for you...
In your action:
$this->form = new StudentCourseForm(array(), array('student_id' => $student_id));
In the form class:
$this->getOption('student_id');