View not populate data after dropdown data selection - entity-framework

I am work on MVC 5 and i fill a dropdown with state name of Country through ViewData and also in my view page i show the every state record. But i want, After selection of Dropdown value in view show only selected state value. this is my code that's not working
Controller
public ActionResult Index(int? id)
{
ViewData["State"] = new SelectList(db.state, "state_id", "name");
if (id!=null)
return View(db.state.Where(x => x.state_id == id));
else
return View(db.state.ToList());
}
View
#Html.DropDownList("ddlstate", (SelectList)ViewData["State"], "Select State", new { onchange = "Index(this.value);", #class = "form-control" })
<table class="table" id="statedetails">
<thead>
<tr>
<th>
State ID
</th>
<th>
State Name
</th>
<th>
City
</th>
<th>
Population
</th>
<th>
Education %
</th>
<th></th>
</tr>
</thead>
#foreach (var item in Model)
{
<tbody>
<tr>
<td>
#Html.DisplayFor(modelItem => item.stateid)
</td>
<td>
#Html.DisplayFor(modelItem => item.statename)
</td>
<td>
#Html.DisplayFor(modelItem => item.city)
</td>
<td>
#Html.DisplayFor(modelItem => item.population)
</td>
<td>
#Html.DisplayFor(modelItem => item.eduction)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.offer_id }) |
#Html.ActionLink("Details", "Details", new { id = item.offer_id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.offer_id })
</td>
</tr>
</tbody>
}
</table>
javascript
<script type="text/javascript">
function Index(id) {
$.ajax({
url: "#Url.Action("Index","State")",
type: "POST",
data: { "id": id }
});
}
</script>

Related

Sort list by order number with record grouping

I have a list of orders. I would like to sort the list in the way that if there are more than one order placed by the same customer, the orders are grouped. It is hard to explain by words so here is an example:
This is the list sorted by Order No:
<table>
<tr>
<th>Customer</th>
<th>Order No</th>
</tr>
<tr>
<td>A</td>
<td>1</td>
</tr>
<tr>
<td>B</td>
<td>2</td>
</tr>
<tr>
<td>C</td>
<td>3</td>
</tr>
<tr>
<td>A</td>
<td>4</td>
</tr>
<tr>
<td>A</td>
<td>5</td>
</tr>
<tr>
<td>D</td>
<td>6</td>
</tr><tr>
<td>C</td>
<td>7</td>
</tr>
</table>
I would like this list to look like this:
<table>
<tr>
<th>Customer</th>
<th>Order No</th>
</tr>
<tr>
<td>A</td>
<td>1</td>
</tr>
<tr>
<td>A</td>
<td>4</td>
</tr>
<tr>
<td>A</td>
<td>5</td>
</tr>
<tr>
<td>B</td>
<td>2</td>
</tr>
<tr>
<td>C</td>
<td>3</td>
</tr>
<tr>
<td>C</td>
<td>7</td>
</tr>
<tr>
<td>D</td>
<td>6</td>
</tr>
</table>
I will be very grateful for any hint :)
Thank you!
You can create a map of customers and orders.
For each map entry create a list of ordernumbers.
Doing so you can sort every order list.
Example:
const list = [
{ customer: 'A', ordernumber: 2 },
{ customer: 'B', ordernumber: 1},
{ customer: 'A', ordernumber: 1 },
{ customer: 'A', ordernumber: 3 }
]
customerOrderMap = {}
list.forEach(element => customerOrderMap[element.customer] = [])
list.forEach(element => customerOrderMap[element.customer].push(element.ordernumber))
Object.keys(customerOrderMap).forEach(key => {
console.log(customerOrderMap[key].sort((a, b) => a - b))
})
console.log(customerOrderMap)

Submit checkbox values Spring MVC

Maybe this question was asked a lot but not in the same way so here is my problem and I hope someone can help.
After having retrieved some research rows from database and returned the results into a List which I have bound to the my Spring MVC Controller Model:
if(!result.hasErrors())
{
try{
List<Question> questionlist = questionservice.findByCategoryAndLevel(questionform.getCategory(),questionform.getLevel());
model.addAttribute("questionlist",questionlist);
return "addExam";
}catch(NullPointerException e)
{
return "redirect:/admin/addexam";
}
}
Here is my view:
<form:form action="addexam" method="POST" modelAttribute="questionlist">
<table class="table table-striped table-bordered table-hover" id="sample_1">
<thead>
<tr>
<th class="table-checkbox">
<input type="checkbox" class="group-checkable" data-set="#sample_1 .checkboxes"/>
</th>
<th>
Category
</th>
<th>
level
</th>
<th>
Type of question
</th>
<th>
Status
</th>
<th>
</th>
</tr>
</thead>
<tbody>
<c:forEach items="${questionlist}" var="question">
<c:choose>
<c:when test="${question.isVisible()}">
<tr class="odd gradeX">
<td>
<input type="checkbox" class="checkboxes" />
</td>
<td>
${question.category.getCategoryName() }
</td>
<td>
${question.level }
</td>
<c:choose>
<c:when test="${question.isSingleChoiceQuestion() }">
<td>Question à choix unique</td>
</c:when>
<c:otherwise>
<td>Question à choix mutiple</td>
</c:otherwise>
</c:choose>
<td class="center">
<c:choose>
<c:when test="${question.getState() == 'Desactivated'}">
<span class="label label-sm label-default"> Desactivated </span>
</c:when>
<c:when test="${question.getState() == 'Activated'}">
<span class="label label-sm label-success"> Activated </span>
</c:when>
<c:when test="${question.getState() == 'Pending'}">
<span class="label label-sm label-warning"> Pending </span>
</c:when>
</c:choose>
</td>
<td>
View
</td>
</tr>
</c:when>
</c:choose>
</c:forEach>
</tbody>
</table>
</form:form>
Now how do I submit the selected items?
yes i wanted to display the question list and then pick the ones i needed via a checkbox
i created a form, it holds the list of Idquestions
public class checkedquestion {
private List<Long> listIdQuestion ;
//getter & setter
}
then added a path attribute to checkbox like below :
<form:form action="submit" method="POST" modelAttribute="checkedquestion">
// .......
<td>
<form:checkbox value="${question.idQuestion}" path="listIdQuestion"/>
</td>
By submitting the list of id i have the ones i needed :
public String add(#ModelAttribute ("checkedquestion") #Valid CheckedQuestion checkedquestion , BindingResult result )
{
if(!result.hasErrors())
{
List<Long> list = checkedquestion.getListIdQuestion();
List<Question> questionlist = questionservice.getQuestion(list);
}
}
it seems to work fine
Give a id/name to input checkbox type as below
<input type="checkbox" class="checkboxes" id="someId" name="someId" value="uniqueValueToEachCheckBox"/>
Then after submitting your form, you can able to access your selected checkbox values in your controller as below.
request.getParameterValues("someId");

jquery form plugin to edit an entire form in place

I've been searching a bit for a jquery plugin that could help me to edit an entire form in place without having to write markup for both the form and displaying the data. Where you can just click "edit" and then the form fields would appear instead of the text, and then save and the form fields would turn into text again.
Does anyone know of one?
Here's the plugin in its crudest form:
(function( $ ){
var YesNo = new Array();
YesNo["true"] = "Yes";
YesNo["false"] = "No";
$.fn.inline = function() {
this.each(function(){
if ($(this).is('table')) {
$(this).find('input, select, textarea').not('[type=button],[type=submit]').each(function(){
if($(this).attr("type")=="checkbox"){
$(this).parent().append("<span class=\"editable\">"+YesNo[$(this).attr('checked')]+"</span>");
$(this).hide();
//$(this).append("<span>"+$(this).val()+"</span>");
$(this).bind('blur',function(){
var t = YesNo[$(this).attr('checked')];
$(this).hide().next().show().text(t);
});
}
else{
$(this).parent().append("<span class=\"editable\">"+$(this).val()+"</span>");
$(this).hide();
//$(this).append("<span>"+$(this).val()+"</span>");
$(this).bind('blur',function(){
var t = $(this).val();
$(this).hide().next().show().text(t);
});
}
});
$(this).find('td').live('dblclick', function(){
$(this).children('.editable').hide().prev().show().focus();
});
}
});
};
})( jQuery );
Call to plugin:
<script type="text/javascript">
$().ready(function () {
$('#dataform').inline();
});
</script>
And the supporting example markup:
<table id="dataform">
<tr>
<td class="label">First Name</td>
<td><input type="text" value="Robin" /> </td>
<td class="label">Last Name</td>
<td><input type="text" value="Maben" /> </td>
</tr>
<tr>
<td class="label">City</td>
<td><input type="text" value="Bangalore" /> </td>
<td class="label">Country</td>
<td><input type="checkbox" checked="checked" /> </td>
</tr>
<tr>
<td class="styleLabel">Status</td>
<td class="styleControl">
<select id="Select1" class="styleDrop">
<option>Active</option>
<option>Inavtive</option>
<option>Pending</option>
</select></td>
</tr>
<tr>
<td>Description</td><td><textarea>Hello World</textarea></td>
</tr>
<tr>
<td>
<input type = "button" value="Click" />
<input type = "submit" />
</td>
</tr>
</table>

Linq query Group By error in ASP.NET MVC 2

I am having a bit of a struggle using linq and returning a list while trying to group.
In my view, I have the following:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcApplication1.Models.Log>>" %>
<table>
<tr>
<th>
ID
</th>
<th>
User
</th>
<th>
NumberDialed
</th>
<th>
Date
</th>
<th>
Time
</th>
<th> </th>
</tr>
<% foreach (var item in Model)
{ %>
<tr>
<td>
<%: item.ID %>
</td>
<td>
<%: item.UserName %>
</td>
<td>
<%: item.NumberDialed %>
</td>
<td>
<%: item.Date %>
</td>
<td>
<%: item.Time %>
<%} %>
</td>
</table>
and in my controller I have:
public ActionResult Tenant()
{
LogEntities db = new LogEntities();
var s = from logs in db.Logs
group logs by logs.UserName;
return View(s.ToList());
}
when I do a normal select it works:
public ActionResult Tenant()
{
using (LogEntities db = new LogEntities())
{
var s = from logs in db.Logs
orderby logs.UserName
select logs;
return View(s.ToList());
}
}
Why is using Group By not working and why it is so different? I want to be able to display the data by groups. How do I accomplish this?
Thanks :)
I think that in order to do a group you need to specify into what you need it to be grouped
var s = (from logs in db.Logs
group logs by logs.UserName into us
select us).ToList();
Then us.Key gives you the username by which it is grouped and us gives all the items that are grouped by this username.
Then you can do:
foreach(var userGroup in s){
var userName = us.Key;
var logs = us.ToList();
}

Is there any way to create form with multiple submit buttons on Spring MVC using annotations?

I'm trying to create simple add/remove form using annotation based Spring MVC.
'Add' functionality comes smoothly, but when I tried to add another button to form i've got stuck.
Here is my code:
Controller actions:
#RequestMapping(value = "/books/documentType.do", method = RequestMethod.GET)
public String getDocType(
#RequestParam(required = false, value = "id") Long id,
ModelMap model) {
DocTypeDTO docType = new DocTypeDTO();
if (id != null)
docType = docTypeConverter.getDTO(id);
model.addAttribute("docType", docType);
return "/books/documentType";
}
#RequestMapping(value = "/books/documentType.do", method = RequestMethod.POST)
public String setDocType(
#ModelAttribute("docType") DocTypeDTO docType,
BindingResult result,
SessionStatus sessionStatus
) {
docTypeValidator.validate(docType, result);
if (result.hasErrors())
return "/books/documentType";
else {
docTypeConverter.saveDTO(docType);
sessionStatus.setComplete();
return "redirect:/books/documentTypes.do";
}
}
Awfully markuped form:
<form:form method="post" commandName="docType" id="editForm">
<table width="100%" border="0" cellpadding="0" cellspacing="0" bgcolor="#dbdbdb">
<tr>
<td></td>
<td>
<table border="0" cellspacing="0" cellpadding="0" width="100%">
<tr>
<td class="spacer"><img src="/images/spacer.gif" width="116" height="1" border="0"/></td>
<td class="spacer"><img src="/images/spacer.gif" width="216" height="1" border="0"/></td>
</tr>
<tr>
<td class="form-cell-text-underlined">Отображать на сайте</td>
<td colspan="2">
<form:checkbox path="shownOnSite"/>
</td>
</tr>
<tr>
<td class="form-cell-text-underlined">Международный</td>
<td colspan="2">
<form:checkbox path="international"/>
</td>
</tr>
<tr>
<td class="form-cell-text-underlined">Внутренний код</td>
<td colspan="2">
<form:input path="internalCode"/>
</td>
</tr>
<tr>
<td class="form-cell-text-underlined">Код</td>
<td colspan="2">
<form:input path="code"/>
<form:errors path="code"/>
</td>
</tr>
<tr>
<td class="form-cell-text-underlined">Код IATA</td>
<td colspan="2">
<form:input path="codeIATA"/>
</td>
</tr>
<tr>
<td class="padded-underlined">Название</td>
<td colspan="2">
<form:input path="name"/>
<form:errors path="name"/>
</td>
</tr>
<tr>
<td class="padded-underlined">Название(Англ.)</td>
<td colspan="2">
<form:input path="nameEn"/>
</td>
</tr>
<tr>
<td colspan="3">
<input type="submit" value="Сохранить">
</td>
</tr>
</table>
</td>
<td></td>
</tr>
</table>
Thanks!
With Spring MVC 3, this is reasonably straight-forward to do with just JSP and Controller. For example, these two submit buttons handle 'previous' and 'save' actions:
<input value="Save" name="save" type="submit" id="btnSave" class="submit_button">
<input value="Previous" name="previous" type="submit" id="btnPrevious" class="submit_button">
Then, in the controller, you accept the input name as a param in the request mapping, along with the controller 'address':
#RequestMapping(value="thisForm.form", params="save")
public String save() {
// save
}
#RequestMapping(value="thisForm.form", params="previous")
public String doPreviousStuff() {
// get mapping for previous page and return
}
If you really want two submit buttons on your form, you can do it with Javascript like this (using jQuery in this example):
<SCRIPT language=JavaScript>
function remove() {
$('#editForm').attr("action", "documentTypeRemove.do");
$("#editForm").submit();
}
</SCRIPT>
...
<button type="button" onclick="remove();">Remove</button>
Then create another RequestMapping in your controller:
#RequestMapping(value = "/books/documentTypeRemove.do", method = RequestMethod.POST)
public String removeDocType(...