Spring form:option - spring-mvc

Is there any way to mark an option as selected by default, much like the selected attribute in the HTML option tag like <option value="value1" selected>?

If the path value of the tag matches the value of options value it will automatically be selected. You don't need anything special

Is there any way to mark an option as selected by default ???
Just use <spring:option Taglib The first one will be automatically selected
<spring:select name="someProperty">
<spring:option value="">Select one</spring:option>
<spring:option value="someValue">Some value<spring:select>
<!--And so on...-->
<spring:select>
or
<spring:select name="someCollection">
<spring:option value="">Select one</spring:option>
<!--Here goes some List added to request-->
<spring:options itemLabel="propertyNameUsedAsLabel" itemValue="propertyNameUsedAsValue"/>
<!--And so on...-->
<spring:select>

I am assuming you are also using Spring MVC. If you have business logic that requires a certain option to be selected by default, move that business logic to the controller - not the JSP.
#RequestMapping(method = RequestMethod.GET)
public ModelAndView helloWorld(){
ModelAndView model = new ModelAndView("HelloWorldPage");
// first we need to give the countries list to the model
model.addObject("countries", countryService.getAllCountries());
// creating the form
ExampleForm form = new ExampleForm();
// setting the default to Germany (de)
form.setCountryCode = "de";
// adding the form (with the default country set) to the model
model.addObject("form", form);
return model;
}
In the JSP, we pass in the countries to the options and spring will automatically have germany selected:
<form:form method="post" commandName="form">
<%-- other fields ... --%>
<form:select path="countryCode">
<form:options items="${countries}" itemValue="countryCode" itemLabel="countryName"/>
</form:select>
<%-- other fields ... --%>
</form:form>

Related

Controller does not receive value from view (implementing search function) on MVC

I'm trying to make a page with a search function. When you first go to the page, all you have is a search bar. When you type something into the search bar and click the "submit" or "search" button, I want the value in the search box to be submitted to the controller as a string. Then, this value can be used in returning the a model back to the page. Here's what I have so far:
Search.cshtml
#{
ViewBag.Title = "Search";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#ViewBag.PageTitle
<h1>Search All Issues</h1>
<form asp-controller="Report" asp-action="Search" method="get">
<input name="searchstr" id="Search" />
<input type="submit" value="Submit" />
</form>
ReportController.cs
[HttpGet]
public ActionResult Search(string test)
{
ViewBag.PageTitle = test;
var report = _context.Reports.ToList();
return View(report);
}
What am I doing wrong here? For now, it would be nice if I can just get that ViewBag.PageTitle to appear on the page. If I can do that, then I can return the report model just the way I want.
Also, a few additional questions. Some of the stuff I've seen on stack overflow has a recommendation to do a Post in the controller. If I do that, the page errors out. Why is a get needed for this? Intuitively, it makes more sense to me to use a Post...
Turns out I was extremely close; Stephen Muecke had the correct answer. I simply needed to change my input name or parameter name.
I made this mistake as I was considering this from a C++/C standpoint where the parameter names can be irrelevant. I see now, though, that with ASP.NET MVC, you need to have the input name match the parameter name.
Thanks for the help!

Pass multiple check box values into Controller in ASP.NET MVC

I have an Enum list. I create these check boxes with the Enum list dynamically.
Here is the Enum list:
[LocalizableDescription(#"BankPos", typeof(Resources.DisplayNames))]
BankPos = 1,
[LocalizableDescription(#"PrarkingPlace", typeof(Resources.DisplayNames))]
PrarkingPlace = 2,
[LocalizableDescription(#"OutdoorPlace", typeof(Resources.DisplayNames))]
OutdoorPlace = 4`
I created the check box with foreach in Html tag .
Here are the check boxes:
<div class="checkbox-container">
<% foreach (var feature in Model.Features)
{%>
<label>
<input type="checkbox" name="q5" />
<span><%= feature.Text %></span>
</label>
<%}
%>
</div>
Up to here every thing is fine. My check boxes are create in correctly .
My problem is, how can I pass these check box values into controller?
As I said I want to pass them multiple.
Here is my controller
[HttpPost]
public ActionResult Review(ReviewMemberRatingViewModel model, HttpPostedFileBase picUpload)
{
return null;
}
You need to include the checkboxes in your model, and bind the values to them. So when you change a value on the model, it will be available in your action result. You could generate your inputs with numerical indexes or there is a great example of what you are doing while taking it a step further with an editor template here.

Spring MVC - using a property file as sort of lookup table for Country field

In my property file, I would have the ff.
country.1=Afghanistan
country.2=Albania
country.3=Algeria
country.4=Andorra
country.5=Angola
and, I'd like to have something like this in my view,
Country: <form:select path="customer">
<form:options items="${countries}" />
</form:select>
which will then produce the following html.
<select>
<option value="1">Afghanistan</option>
<option value="2">Albania</option>
<option value="3">Algeria</option>
<option value="4">Andorra</option>
<option value="5">Angola</option>
</select>
Do you have some suggestions on how to achieve this?
Thanks.
You could just have a single property that had your list of countres:
countries=Afghanistan,Albania,...
You can get access to your properties file in you view controller by annotating the class with #PropertySource("classpath:countires.properties") and autowiring in an Environment variable:
#Controller
#PropertySource("classpath:countries.properties")
public class PersistenceConfig {
#Autowired
private Environment env;
Then you can get a property by calling env.getProperty(""). You can add that to your model for you main view:
#RequestMapping(value={"/","/index","/index.htm","index.html"})
public String indexHtml(ModelMap model) {
model.addAttribute("countries", env.getProperty("whatever"));
return "index"; // or whatever the name of your view is
Then in your index.jsp you can simply use ${countries} to get the value(s) and do whatever you want with them. At some point you'll obviously want to parse the whole string into an array.
It is also possible to read the properties file directly into the .jsp file. Plenty of threads around about that.

TextBoxFor producing a blank field

I have a weird problem in my MVC app.
When the user selects a date from a drop down, it clears the StartDate and EndDate fields.
I have the following fragment of code:
<label>Start date: #Model.StartDate</label>
#Html.TextBoxFor(s => s.StartDate)
The weird thing is that you can wee where I'm outputting it in the label, the date comes out there. The textbox is unpopulated.
I've checked the produced markup and the textbox is not being populated.
<label>Start date: 19/05/2013</label>
<input id="StartDate" name="StartDate" type="text" value="" /> <br />
What am I missing here?
To add a little bit more information, when the page is initially populated the default start and end date are output. There is a bit of jQuery that empties those fields when a <select> is changed. If I comment that bit out then the fields retain their previous values as opposed to blank. Essentially, whatever is submitted to the server is output rather than the value in the model.
Essentially, whatever is submitted to the server is output rather than the value in the model.
This behaviour is actually by design. The idea being that generally the user would expect to see in the text box what they submitted to the server.
See here for a detailed explanation, and a work around.
Instead of doing this
<label>Start date: #Model.StartDate</label>
#Html.TextBoxFor(s => s.StartDate)
You should do this
<label id="someId"></label>
#Html.TextBoxFor(s => s.StartDate,new{#id="startdate"})
and using jquery on change event on your textbox you can set lablel
$("#startdate").change(function(){
var date="Start Date:"+$(this).val();
$("#someid").html(date);
});
Thinks that your model is a class named What like this:
public class What
{
public string StartDate { get; set; }
}
Then, think that your application is "MyApplication", you need to add to the view as if the view is stronglytyped:
#using MyApplication.Models;
#inherits System.Web.Mvc.WebViewPage<What>
Then all should we run as you expect

ASP.NET MVC View User Control - how to set IDs?

I need a dropdown list on my page that will allow a user to select their state. Since this is probably a control that will be used elsewhere, I thought it would be a good idea to create an MVC View User Control that could be reused.
I was thinking the control would look something like this:
<select name="" id="">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
</select>
And the code in my view would be something like:
<%= Html.RenderPartial("StateDropdownControl") %>
My question is, what's the best way to set the name and id on the control? I'd want to make sure I could have multiple instances of this control on one page, if needed. Also, I'd want to be able to send in the state that should be selected by default.
Would I do it with ViewData somehow?
Corey is on to the right solution. I think declaring specific Model objects for your view makes the views VERY simple and as a side bonus makes them dirt easy to test.
So instead of just passing the ID as the object, you'd probably want to create your own Model object to pass in.
It could look something like this:
public class StateDropDownPresentationModel
{
public string DropDownID { get; set; }
public string SelectedState { get; set; }
}
Obviously, keep adding whatever you need to this model to make your view correct.
Then, you could call it like this:
<%= Html.RenderPartial("/someDirectory/SomeControl.ascx", new StateDropDownPresentationModel { DropDownID = "MyID", SelectedState = "IL" } %>
Then just make sure you put in checks for things like ID being null/blank (that should probably throw an error) and SelectedState being null/blank.
Well you can pass object data to the RenderPartial method in conjunction to the User Control to render, so you could easily do the following:
<%= Html.RenderPartial("/someDirectory/SomeControl.ascx", "MyID") %>
and in the UserControl do the following:
<select name="<%=ViewData.Model%>" id="<%=ViewData.Model%>">
....
Just to be sure, a better way to handle it is to make a simple DTO (data transfer object) to hold that information so you can pass more information to your user control, that you will inevitably need.
Example:
class ComboData
{
string ID {get;set;}
string CssClass {get;set;}
//Other stuff here
}
<%
var comboData = new ComboData {ID = "myID", CssClass = "comboStyle" }
%>
<%= Html.RenderPartial("/someDirectory/SomeControl.ascx", comboData) %>
<select name="<%=ViewData.Model.ID%>" id="<%=ViewData.Model.ID%>" class="<%=ViewData.Model.CssClass%>">
....
Make sure you set the Code behind for the user control to be a generic of type ComboData for this example.
Take a look at the Html.DropDownList helper method. It has a number of overloads that allow you to pass the list data and set the selected item. the simplest version just sets the name of the select.
<%= Html.DropDownList("SelectStates"); %>
If there is a value in the ViewData["SelectStates"] that is of type MultiSelectList then the list will be automatically populated.

Resources