Get DropDownList value into POST method - drop-down-menu

I am working on this ASP.NET Core MVC where I have this DropDownLisit which gets its values from Controller using ViewBag.DishTypes. However, upon submitting the form, the POST method is not getting the value of the option selected in the DropDownList. The code snippets are as follows:
Controller: GET Method
var allDishTypes = _context.DishType
.ToList()
.Select(dt => new SelectListItem { Value = dt.DishTypeId.ToString(), Text = dt.DishTypeName.ToString() }).ToList();
ViewBag.DishTypes = allDishTypes;
return View();
View
<form asp-controller="Home" asp-action="AddMenuItems">
<div class="row">
<label class="my-1 mr-2" for="inlineFormCustomSelectPref">Dish Type</label>
<div class="input-group">
<div class="fg-line form-chose">
<label asp-for="DishTypeId" class="fg-labels" for="DishTypeId">Dish Type</label>
<select asp-for="DishTypeId" asp-items="ViewBag.DishTypes" class="form-control chosen" data-placeholder="Choose Dish Type" required name="dishtype" id="dishtype">
<option value=""></option>
</select>
</div>
</div>
....
Controller: POST Method
[HttpPost]
public IActionResult AddMenuItems([Bind("DishTypeId, DishName, Cost")] Dishes dishesObj)
{
....
}

the POST method is not getting the value of the option selected in the DropDownList
Note that you specified a name=dishtype within your code. By this way, the field name is
always the same as this name attribute, i.e, dishtype instead of DishTypeId, which will not be recognized by ASP.NET Core by default.
To fix that issue, simply remove that attribute such that it uses asp-for to generate the name attribute automatically:
<select asp-for="DishTypeId" asp-items="ViewBag.DishTypes"
class="form-control chosen" data-placeholder="Choose Dish Type" required
name="dishtype" id="dishtype"
>
<option value=""></option>
</select>

Related

Thymeleaf + Spring. Using an object method instead another block in the form

I have a typical updateUser form built with Thymeleaf + Spring. I can list the user roles but I am trying to put these into a selectbox component. I am struggling with this line th:selected="${user.hasRole(role.role)}". Now, I know this component works and that is only a matter of access a boolean function to enable it. I am trying to reference a function of the form object using the select th:object. My syntax doesn't work. I have also try to access that function just like previous input tags would (only using the name without the object itself .ie username or in this case hasRole(). That doesn't work either.
<form th:object="${user}"
th:action="#{'/admin/usermanagement/adduser'} " method="post">
<div class="row">
<div class="col-md-3 form-group">
<label>Username:</label> <input type="text" class="form-control"
th:field="*{username}" />
</div>
</div>
<div class="col-md-3">
<h5>Roles :</h5>
</div>
<select class="js-example-basic-multiple" style="width: 75%"
name="froles" id="froles" multiple="multiple">
<option th:each="role : ${roles}" th:value="${role.role}"
th:selected="${user.hasRole(role.role)}"
th:text="${role.role}"></option>
</select>
<button type="submit" class="btn btn-primary">Submit</button>
In fact, my problem is types. th:selected="${user.hasRole(role.role)}" is a string and should be th:selected="${user.hasRole(role)}". I have both method in the domain object so that is fine.
th:value="${role.role}" is wrong for persistence. I want to return role but I get the following error message when I use role.role
codes [user.roles,roles]; arguments []; default message [roles]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.List' for property
and Java null exception when I use "${role}"

Why it appears the erro Non-static method should not be called statically in this context?

Im trying to use this package " dannyvankooten/laravel-vat" to load a select menu with the countries and then validate the vat number inserted in the input type text.
So I have this in a form:
<div class="form-group font-size-sm">
<select class="form-control" name="country" id="country">
#foreach($countries as $country)
<option value="{{$country}}">{{$country}}</option>
#endforeach
</select>
</div>
<div class="form-group font-size-sm">
<label for="vat" class="text-gray">VAT</label>
<input type="text" id="vat" name="vat" class="form-control" value="">
</div>
In the RegistrationController I have in a method this to return the $countries to the view to the select menu:
$countries = Countries::all();
But it appears:
Non-static method DvK\Laravel\Vat\Countries::all() should not be called statically
Do you know why?
In your specific case (laravel & facades), it's because you have imported the wrong class in your controller.
You need to replace
use DvK\Laravel\Vat\Countries;
with
use DvK\Laravel\Vat\Facades\Countries;
like shown in the readme # https://github.com/dannyvankooten/laravel-vat
The facade is what provides the static accessor e.g. Countries::all()
all is not a static method in the Countries class. You should first create an instance of Countries and then call its all method:
$countries = new Countries();
$allCountries = $countries->all();
return view('congress.registration', ['countries' => $allCountries]);

thymeleaf how to pass many objects?

how to pass many objects in one form? becouse like that not working.... help me please
<form class="form-control" action="#" th:action="#{'/'}" method="post">
<select>
<option th:each="city :${cities}" th:value="${city.getId()}" th:text="${city.getName()}"/>
</select>
<select>
<option th:each="category :${categories}" th:value="${category.getId()}" th:text="${category.getDescirption()}">
</option>
</select>
//this line isnt correct:
<a class="btn btn btn-primary btn-sm" href="#"
th:href="#{'/todo/done?id=' + ${city.id} + '&name=' + ${category.name}}">done</a>
</form>
You add each object as named model attribute. Example
#RequestMapping(value = "message", method = RequestMethod.GET)
public String messages(Model model) {
model.addAttribute("cities", citiesRepository.getAll());
model.addAttribute("categories", citiesRepository.getAll());
return "message/list";
}
Personally I find it more readable to have single object as model attribute. That object has fields for each actual attribute.
See official documentation for more details https://www.thymeleaf.org/doc/articles/springmvcaccessdata.html
In your example you are not using th:each correctly.
You should have th:each as select level (not at option level) then refer to individual items in nested select elements.
like
<select th:each="city :${cities}">
<option th:value="${city.getId()}" th:text="${city.getName()}"/>
</select>
In your last example you are refering to ${city.id} and ${category.name} but city and category are not defined (probably thymleaf error message tells you that).
What exactly you want to achieve? Do you want to link with selected city and category? If so, you need separate model attributes like
selectedCity and selectedCatetory.

MVC3 Validation on view remains invalid due to DropDownList

I've had to add a manual DropDownList within my Create View giving the user 2 options of 'input '.
Now the validation doesn't work when I come to save the information even though my code is now:
<div class="editor-field">
<select name="type" id="type">
<option value></option>
<option value="1" id="apple">Apple</option>
<option value="2" id="banana">Banana</option>
</select>
<span class="field-validation-valid" data-valmsg-for="type" data-valmsg-replace="true"></span>
How do I get the built in validation back on the 'Type'field. I have this as 'Required' within the model class.
your drop-down Name and ID should be a property of your model.
<select name="type" id="type">
include type as a Property in your Model and make it required.
public class myModel{
[Required]
public string type{get; set;}
}
being type a c# keyword I would suggest you to use something else as your property name for example "FruitDD"

MVC3 - Understanding POST with a button

How does one obtain the form data after submitting it?
<form target="_self" runat="server">
<p>
<select id="BLAHBLAH2">
<option>2010</option>
<option>2011</option>
<option>2012</option>
<option>2013</option>
</select>
<input type="submit" runat="server" value="Change Year" />
</p>
</form>
This hits the controller's Index method. But, there's nothing in Request.Form. Why?
Second, can I use
<input type="button" instead of type=submit? That is, without introducing ajax via onclick.
Finally, how do I submit to a different method in the controller, e.g. Create?
Try removing those runat server tags. They should not be used in ASP.NET MVC. Also your select doesn't have a name. If an input element doesn't have a name it won't submit anything. Also your option tags must have value attributes which indicates what value will be sent to the server if this options is selected:
<form action="/Home/Create" method="post">
<p>
<select id="BLAHBLAH2" name="BLAHBLAH2">
<option value="2010">2010</option>
<option value="2011">2011</option>
<option value="2012">2012</option>
<option value="2013">2013</option>
</select>
<input type="submit" value="Change Year" />
</p>
</form>
But the correct way to generate forms in ASP.NET MVC is to use HTML helpers. Depending on the view engine you are using the syntax might be different. Here's an example with the Razor view engine:
#model MyViewModel
#using (Html.BeginForm("Create", "Home"))
{
<p>
#Html.DropDownListFor(x => x.SelectedYear, Model.Years)
<input type="submit" value="Change Year" />
</p>
}
Here you have a strongly typed view to some given view model:
public class MyViewModel
{
public string SelectedYear { get; set; }
public IEnumerable<SelectListItem> Years
{
get
{
return Enumerable
.Range(2010, 4)
.Select(x => new SelectListItem
{
Value = x.ToString(),
Text = x.ToString()
});
}
}
}
which is populated by some controller action that will render this view:
public class HomeController: Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
[HttpPost]
public ActionResult Create(MyViewModel model)
{
... model.SelectedYear will contain the selected year
}
}
None of your <option> tags have a value:
...
<option value="2010">2010</option>
...
As noted by David, runat="server" is most definitely a WebForms thing, so you can 86 that.
If you want to submit to a different method on your controller you just need to specify the URL for that method.
Easy way using Html.BeginForm:
#using (Html.BeginForm("AnotherAction", "ControllerName")) {
<!-- Your magic form here -->
}
Using Url.Action
<form action="#Url.Action("AnotherAction")" method="POST">
<!-- Your magic form here -->
</form>
You can also use
In Controller
int Value = Convert.ToInt32(Request["BLAHBLAH2"]); //To retrieve this int value
In .cshtml file use
<select id="IDxxx" name="BLAHBLAH2">
//Request[""] will retrieve the VALUE for the html object ,whose "name" you request.

Resources