can somebody help me..
this is my Code:
Index.cshtml
<!DOCTYPE html>
<html>
<head>
<title>jQuery With Example</title>
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
$(function () {
$('.chkview').change(function () {
$(this).closest('tr').find('.chkitem').prop('checked', this.checked);
});
$(".chkitem").change(function () {
var $tr = $(this).closest('tr'), $items = $tr.find('.chkitem');
$tr.find('.chkview').prop('checked', $items.filter(':checked').length == $items.length);
});
});
function Save() {
$.ajax({
url: #Url.Action("Index", "Home" , "Index"),
type: "POST",
data: formData ,
dataType: "json",
success: function(data){
alert(data.RoleID)
},
error: function(e){
debugger;
}
}
</script>
</head>
<body>
<h2>Access Control-Home</h2>
<br />
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { RoleID="RoleID" }))
{
<input type="hidden" name="RoleID" value="1" id="RoleID" />
<table id="mytable">
<tr>
<td>View</td>
<td>Insert</td>
<td>Update</td>
<td>Delete</td>
</tr>
<tr>
<td>Administrator</td>
<td>
<input type="checkbox" class="chkview chkview-1" />
</td>
<td>
<input type="checkbox" class="chkitem chkitem-1" />
</td>
<td>
<input type="checkbox" class="chkitem chkitem-1" />
</td>
<td>
<input type="checkbox" class="chkitem chkitem-1" />
</td>
</tr>
<tr>
<td>Free User</td>
<td>
<input type="checkbox" class="chkview chkview-2" />
</td>
<td>
<input type="checkbox" class="chkitem chkitem-2" />
</td>
<td>
<input type="checkbox" class="chkitem chkitem-2" />
</td>
<td>
<input type="checkbox" class="chkitem chkitem-2" />
</td>
</tr>
</table>
<br />
<button type="submit" class="buttons buttons-style-1" onclick="Save()">Save</button>
}
</body>
</html>
HomeController.cs
[HttpPost]
public ActionResult Index(string RoleID)
{
var _roleID = RoleID;
return View();
}
i want to ask 2 question.
how i can parsing value of list checked checkbox using ajax? i want parsing classname of checkbox which i checked example i need list of array if i checked row administrator, { 'chkinsert-1','chkupdate-2' }
how i can get value collection of array in controller post?
example:
public ActionResult Index(string RoleID, array[] collChecbox) contents of collChecbox = { 'chkinsert-1','chkupdate-2'} in accordance with the user checked of checkbox input.
can somebody help me??
Why don't you use Ajax.BeginForm() this makes so easy to send posted form value.
Also, you should create proper model first.
MODEL
public class UserRole
{
public Administrator Administrator { get; set; }
public FreeUser FreeUser { get; set; }
}
public class Administrator
{
public int Checkbox1 { get; set; }
}
public class FreeUser
{
public int Checkbox1 { get; set; }
}
Do following in View.
#model Model.UserRole
<div id="result"></div>
#using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "result" }))
{
<input type="hidden" name="RoleID" value="1" id="RoleID" />
<table id="mytable">
<tr>
<td>View</td>
<td>Insert</td>
<td>Update</td>
<td>Delete</td>
</tr>
<tr>
<td>Administrator</td>
<td>
#Html.CheckBoxFor(m => m.Administrator.Checkbox1)
</td>
</tr>
<tr>
<td>Free User</td>
<td>
#Html.CheckBoxFor(m => m.FreeUser.Checkbox1)
</td>
</tr>
</table>
<br />
<button type="submit" class="buttons buttons-style-1" onclick="Save()">Save</button>
}
Controller action
[HttpPost]
public ActionResult Index(UserRole model)
{
return View();
}
Also don't forget to include ajax library.
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
Related
I have a Many-to-Many-Relationship between FishingDay and Fisherman.
Here is my Entity-Class FishingDay:
#Entity
#Table(name = "FISHING_DAY")
public class FishingDay {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long fishingDayId;
#ManyToMany
#JoinTable(name = "fisherman_day",
joinColumns = #JoinColumn(name = "fishing_day_id"),
inverseJoinColumns = #JoinColumn(name = "fisherman_id"))
private Set<Fisherman> fishermen = new HashSet<Fisherman>();
// more properties, getter & setter ...
Here is my Entity-Class Fisherman:
#Entity
#Table(name = "FISHERMAN")
public class Fisherman {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long fishermanId;
#JsonIgnore
#ManyToMany(mappedBy = "fishermen")
private Set<FishingDay> fishingDays = new HashSet<FishingDay>();
// more properties, getter & setter ...
The Add- and Edit-Methods of FishingDay-ControllerClass:
public static final String FORM_NAME_SINGLE = "FishingDaySingleList";
private static final String REDIRECT_URL = "redirect:/fishingDays/show";
#GetMapping("/add")
public ModelAndView add()
{
LOGGER.info(LogUtils.info(CLASS_NAME, "add"));
ModelAndView mv = new ModelAndView(FORM_NAME_SINGLE);
mv.addObject("add", true);
mv.addObject("fishingDay", new FishingDay());
List<Fisherman> fishermen = fishermanRepository.findAll();
mv.addObject("fishermen", fishermen);
return mv;
}
#GetMapping("/edit/{fishingDayId}")
public ModelAndView edit(#PathVariable long fishingDayId) {
LOGGER.info(LogUtils.info(CLASS_NAME, "edit", String.format("%d", fishingDayId)));
ModelAndView mv = new ModelAndView(FORM_NAME_SINGLE);
Optional<FishingDay> optionalFishingDay = fishingDayRepository.findById(fishingDayId);
if (optionalFishingDay.isPresent()) {
FishingDay fishingDay = optionalFishingDay.get();
List<Fisherman> fishermen = fishermanRepository.findAll();
mv.addObject("add", false);
mv.addObject("fishermen", fishermen);
mv.addObject("fishingDay", fishingDay);
}
return mv;
}
#PostMapping(value = "/addEdit")
public ModelAndView addEdit(#Valid #ModelAttribute FishingDay fishingDay, BindingResult bindingResult) {
boolean error = false;
LOGGER.info(LogUtils.info(CLASS_NAME, "addEdit", String.format("%s %b", fishingDay, error)));
ModelAndView mv = new ModelAndView();
if (!error) {
error = bindingResult.hasErrors();
}
if (!error) {
try {
fishingDayRepository.save(fishingDay);
mv.setViewName(REDIRECT_URL);
}
catch (Exception e) {
e.printStackTrace();
LOGGER.error(LogUtils.info(CLASS_NAME, "addEdit"));
mv.addObject("error", e.getCause().getCause().getLocalizedMessage());
error = true;
}
}
else {
mv.setViewName(FORM_NAME_SINGLE);
mv.addObject("add", fishingDay.getFishingDayId() == null);
}
return mv;
}
Here is the FishingDaySingleList:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title th:text="#{fishingDay.caption.plural}"></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/webjars/bootstrap/css/bootstrap.min.css">
<script src="/webjars/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<form action="#" th:action="#{/fishingDays/addEdit}"
th:object="${fishingDay}" method="POST" enctype="application/x-www-form-urlencoded"
class="row g-3 needs-validation" novalidate>
<table id="table1" class="table table-striped table-responsive-md">
<tr>
<td th:text="#{fishingDay.fishingDayId}"></td>
<td><input type="text" th:field="*{fishingDayId}" size=10 readonly class="form-control"></td>
</tr>
<tr>
<td th:text="#{fishingDay.fishingDate}"></td>
<td><input type="date" th:field="*{fishingDate}" size=50 placeholder="" class="form-control"></td>
<td class="alert alert-danger" th:if="${#fields.hasErrors('fishingDate')}" th:errors="*{fishingDate}">
FishingDate Error
</td>
</tr>
<tr>
<td th:text="#{fishingDay.waterTemperature}"></td>
<td><input type="text" th:field="*{waterTemperature}" size=50 placeholder="" class="form-control"></td>
<td class="alert alert-danger" th:if="${#fields.hasErrors('waterTemperature')}"
th:errors="*{waterTemperature}">WaterTemperature Error
</td>
</tr>
<tr>
<td th:text="#{fishingDay.sunrise}"></td>
<td><input type="time" th:field="*{sunrise}" size=50 placeholder="" class="form-control"></td>
<td class="alert alert-danger" th:if="${#fields.hasErrors('sunrise')}" th:errors="*{sunrise}">Sunrise
Error
</td>
</tr>
<tr>
<td th:text="#{fishingDay.sunset}"></td>
<td><input type="time" th:field="*{sunset}" size=50 placeholder="" class="form-control"></td>
<td class="alert alert-danger" th:if="${#fields.hasErrors('sunset')}" th:errors="*{sunset}">Sunset
Error
</td>
</tr>
<tr>
<td th:text="#{fisherman.caption.singular}"></td>
<td>
<select class="form-control" id="fishermen" th:field="*{fishermen}" oninput="showStuff()">
<option value="-1" th:text="#{option.choose}"></option>
<option th:each="fm:${fishermen}"
th:value="${fm.fishermanId}"
th:text="${fm.fullName} + ' (' + ${fm.nickname} + ')'"
th:id="fmId">
</option>
</select>
</td>
<td class="alert alert-danger" th:if="${#fields.hasErrors('fishermen')}" th:errors="*{fishermen}"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" class="btn btn-primary" th:value="#{button.save}"/></td>
</tr>
</table>
<p class="alert alert-danger" th:if="${error!=null}" th:text="${error}"></p>
</form>
</div>
</body>
</html>
Everything is working fine, but I want to create the same dropdown dynamically after a value is selected and append it to the previous dropdown. Moreover, after every selection the value should be removed from list. This should be done until submit or the list is empty.
Here is an image for demonstration
I guess it is possible with javascript? But I've never had anything to do with it before and that's why I run into many troubles when I try to realize this on my own.
Yes, JavaScript can handle this. Try this one:
<select name="val" size="1" id="fishermen" onchange="doSomething();">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
<option value="E">E</option>
</select>
<script>
function doSomething() {
var selectedFisherman = document.getElementById("fishermen");
for (var i=0; i<selectedFisherman .length; i++) {
if (selectedFisherman.options[i].value == selectedFisherman.value) {
selectedFisherman[i].setAttribute("hidden", "hidden");
}else {
selectedFisherman[i].removeAttribute("hidden");
}
}
}
</script>
I am using .NET CORE MVC for making some forms for the user to add people to a system (A manual process). One of the forms I've got is a simple multi-add user form that allows the user to enter names on the form and click submit, where it is then serialized and converted into a PDF document to be saved to the local machine.
I wanted to make this with a dynamic HTML Table in mind so I've got the following setup. The intent here is to allow a table to start initially with a single empty, editable row and give the ability to add rows as they need, while binding each row to a list of objects on the model.
User class
[Serializable]
public class User
{
[Display(Name = "M.I.")]
public string MiddleInitial { get; set; }
[Display(Name = "Suffix")]
public string NameSuffix { get; set; }
[Required(AllowEmptyStrings = false)]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required(AllowEmptyStrings = false)]
[Display(Name = "Last Name")]
public string LastName { get; set; }
}
MultiAddUser class
[Serializable]
public class MultiAddUser
{
[Required]
[Display(Name = "Start Date")]
public DateTime StartDate { get; set; }
public List<User> Users { get; set; }
public MultiAddUser()
{
Users = new List<User>();
}
}
My view has the following code that displays the basic table with inputs in the cells with the ability to add cells on the fly.
#using Contract
#model MultiAddUser
#section Scripts{
<script>
function addRow() {
var table = document.getElementById("MultiAddUserTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
cell1.innerHTML = '<input type="text" />';
var cell2 = row.insertCell(1);
cell2.innerHTML = '<input type="text" />';
var cell3 = row.insertCell(2);
cell3.innerHTML = '<input type="text" />';
var cell4 = row.insertCell(3);
cell4.innerHTML = '<input type="text" />';
}
</script>
}
<style>
input {
width: 100%;
}
</style>
<body>
<h2 class="formtitle">ADD MULTIPLE USERS</h2>
<form method="post" asp-action="AddMultipleUsers" id="addMultiUsers">
<div class="form-group">
<div class="form-row">
<div class="form-group col-sm-2">
<label asp-for="StartDate"></label>
<input type="date" asp-for="StartDate" class="form-control" />
<span asp-validation-for="StartDate" class="text-danger"></span>
</div>
</div>
<table id="AddMultipleUsersTable">
<tr>
<th>First Name</th>
<th>Middle Initial</th>
<th>Last Name</th>
<th>Suffix</th>
</tr>
<tr>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
</tr>
</table>
<button type="button" onclick="addRow()">Add</button>
<hr />
<div class="form-row">
<div id="submitbutton">
<input id="submit" class="btn btn-primary btn-lg" style="background-color: #4CAF50; color:white;" type="submit" />
</div>
</form>
</body>
Now normally with ASP.NET Core MVC you would just have something like asp-for="#Model.Property[IndexIfNeeded]" in the input tag helper but since the list starts empty and is not bound by a database, I'm having trouble piecing together how I would go about adding each new row as a new item to the list on the model once the entire form is submitted.
I may be over complicating this since the data never needs to be entered into a database, but it does need to be serialized and converted into a PDF document and be printed at the end of the process so any insight as to alternative methods to accomplish that would be appreciated.
In summary, How can I bind the rows / columns added dynamically to this table to my model objects, while maintaining validation rules on each required property?
Since your data is not associated with the database, I recommend that you create public variables to store the added and new added data.
And the 'td' tag in view does not support the 'asp-for' attribute, so you can add the input box in 'td' to add new data.
public class HomeController : Controller
{
public static MultiAddUser multiAddUser = new MultiAddUser { };
public static List<User> users = new List<User> { };
public IActionResult Index()
{
ViewBag.UserList = multiAddUser.Users;
return View();
}
public IActionResult Add(User user)
{
if (!ModelState.IsValid)
{
ViewBag.UserList = multiAddUser.Users;
return View("Index");
}
users.Add(user);
multiAddUser.Users = users;
return RedirectToAction("Index");
}
}
Index.cshtml:
#model WebApplication_core.Models.User
#{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Index</h1>
<form asp-controller="Home" asp-action="Add">
<table id="MultiAddUserTable" class="table">
<tr>
<th>First Name</th>
<th>Middle Initial</th>
<th>Last Name</th>
<th>Suffix</th>
</tr>
#foreach (var item in (IEnumerable<WebApplication_core.Models.User>)ViewBag.UserList)
{
<tr>
<td>#item.FirstName</td>
<td>#item.MiddleInitial</td>
<td>#item.LastName</td>
<td>#item.NameSuffix</td>
</tr>
}
<tr>
<td contenteditable="true">
<input id="Text1" type="text" asp-for="#Model.FirstName" />
<br /><span asp-validation-for="#Model.FirstName" class="text-danger"></span>
</td>
<td contenteditable="true">
<input id="Text2" type="text" asp-for="#Model.MiddleInitial" />
<br /><span asp-validation-for="#Model.MiddleInitial" class="text-danger"></span>
</td>
<td contenteditable="true">
<input id="Text3" type="text" asp-for="#Model.LastName" />
<br /> <span asp-validation-for="#Model.LastName" class="text-danger"></span>
</td>
<td contenteditable="true">
<input id="Text4" type="text" asp-for="#Model.NameSuffix" />
<br /> <span asp-validation-for="#Model.NameSuffix class="text-danger"></span>
</td>
</tr>
</table>
<input id="Button1" type="submit" value="Add" />
</form>
Here is the result :
Update(2020/3/5) :
public class HomeController: Controller
{
public static List<User> users = new List<User> { new User { } };
public static MultiAddUser multiAddUser = new MultiAddUser
{
Users = users
};
public IActionResult Index()
{
ViewBag.UserList = multiAddUser.Users;
return View();
}
public IActionResult Add(List<User> userLists)
{
if (!ModelState.IsValid)
{
ViewBag.UserList = multiAddUser.Users;
return View("Index");
}
users = userLists;
users.Add(new User { });
multiAddUser.Users = users;
return RedirectToAction("Index");
}
}
Index.cshtml:
#model IList<WebApplication_core.Models.User>
#{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
var Model = (IList<WebApplication_core.Models.User>)ViewBag.UserList;
}
<h1>Index</h1>
<form asp-controller="Home" asp-action="Add">
<table id="MultiAddUserTable" class="table">
<tr>
<th>First Name</th>
<th>Middle Initial</th>
<th>Last Name</th>
<th>Suffix</th>
</tr>
#for (int i = 0; i < Model.Count(); i++)
{
<tr>
<td>
<input id="Text1" type="text" asp-for="#Model[i].FirstName" />
<br /><span asp-validation-for="#Model[i].FirstName" class="text-danger"></span>
</td>
<td>
<input id="Text2" type="text" asp-for="#Model[i].MiddleInitial" />
<br /><span asp-validation-for="#Model[i].MiddleInitial" class="text-danger"></span>
</td>
<td>
<input id="Text3" type="text" asp-for="#Model[i].LastName" />
<br /> <span asp-validation-for="#Model[i].LastName" class="text-danger"></span>
</td>
<td>
<input id="Text4" type="text" asp-for="#Model[i].NameSuffix" />
<br /> <span asp-validation-for="#Model[i].NameSuffix" class="text-danger"></span>
</td>
</tr>
}
</table>
<input id="Button1" type="submit" value="Add" />
</form>
Here is the new result :
I am having a main view and few partial views.
The main view is something which displays the list of registered users like this :
The main view code :
#model WebApplication9.Models.User
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link ref="~/Styles/UserManagement.css" rel="stylesheet" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<p>
<button type="submit" name="btnDefineTraj" onclick="AddUserBtnClick()" id="button1">Create New User</button>
</p>
<div hidden id="divAddUser" title="Add new user" style="border-radius: 7px">
#Html.Partial("~/Views/UserManagement/CreateUser.cshtml")
</div>
<div hidden id="divEditUser" title="Edit user" style="border-radius: 7px">
#Html.Partial("~/Views/UserManagement/EditUser.cshtml", Model)
</div>
<table>
<tr>
<th>UserID
</th>
<th>Username
</th>
<th>Password
</th>
<th>FirstName
</th>
<th>LastName
</th>
<th>DisplayName
</th>
<th>Email
</th>
<th>Pref. Language
</th>
<th>CreatedBy
</th>
<th>CreatedTime
</th>
<th>ModifiedTime
</th>
<th>IsAdmin
</th>
<th>IsActive
</th>
<th></th>
</tr>
#foreach (var item in Model.usersList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.userId)
</td>
<td>
#Html.DisplayFor(modelItem => item.userName)
</td>
<td>
#Html.DisplayFor(modelItem => item.password)
</td>
<td>
#Html.DisplayFor(modelItem => item.firstName)
</td>
<td>
#Html.DisplayFor(modelItem => item.lastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.displayName)
</td>
<td>
#Html.DisplayFor(modelItem => item.email)
</td>
<td>
#Html.DisplayFor(modelItem => item.languagePreference)
</td>
<td>
#Html.DisplayFor(modelItem => item.createdBy)
</td>
<td>
#Html.DisplayFor(modelItem => item.createdTime)
</td>
<td>
#Html.DisplayFor(modelItem => item.modifiedTime)
</td>
<td>
#Html.DisplayFor(modelItem => item.isAdmin)
</td>
<td>
#Html.DisplayFor(modelItem => item.isActive)
</td>
<td>
<button type="submit" name="btnEditUser" onclick="EditUserBtnClick(#item.userId)" id="buttonEdit">
<img src="~/Images/edit-icon.png" width="20" height="20" />
</button>
</td>
<td>
<button type="submit" name="btnDeleteUser" onclick="DeleteUserBtnClick(#item.userId)" id="buttonDelete">
<img src="~/Images/delete-icon.png" width="20" height="20" /></button>
#* #Html.ActionLink("Edit", "EditUser", new { id=item.userId } ) |
#Html.ActionLink("Delete", "DeleteUser", new { id=item.userId })*#
</td>
</tr>
}
</table>
</body>
</html>
My model class User code is :
public class User
{
public int UserId { get; set; }
public string userName { get; set; }
public string passWord { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string displayName { get; set; }
public string emailID { get; set; }
public string languagePreference { get; set; }
public bool isAdministrator { get; set; }
public bool isActive { get; set; }
public IEnumerable<usermaster> usersList{ get; set; }
public usermaster EditUserData { get; set; }
}
As you can see, the table is loaded from usersList in the model.
Now I am trying to implement the edit user functionality. When user clicks on edit button I am opening a partial view :
<div hidden id="divEditUser" title="Edit user" style="border-radius: 7px">
#Html.Partial("~/Views/UserManagement/EditUser.cshtml", Model)
</div>
by passing the id to the controller and getting back the user data so that it can be displayed in the new partial view
function EditUserBtnClick(userid) {
$.ajax({
type: "POST",
url: "/UserManagement/EditUser",
data: JSON.stringify({ userID: userid }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (edituserDataObj) {
if (msg != null) {
$("#divEditUser").dialog({ width: 350 });
}
else {
$('#lblResult').val("Failed to delete user.");
}
},
error: function () {
return "error";
}
});
I am getting the edituserDataObj properly here. But I am not sure how to pass it to the partial view EditUser.cshtml. I tried to edit the model by adding the new edit user data to a model class property public usermaster EditUserData { get; set; }. But when I access this from my partial view, the data is null.
[HttpPost]
public JsonResult EditUser(int userID)
{
var user = DBManager.Instance.GetUserData(userID);
return Json(user);
}
Is there any way to pass the edit user data to the partial view?
I am learning spring mvc rest programming and got stuck at the below issue.
I have an item page in JSP which is used for adding a new item as well as editing an item.
What I did here is (not sure if this is the right approach), I have a controller method
#RequestMapping(value = "/item/{id}", method = RequestMethod.GET)
public String addEditItem(Model model, Principal principal, #PathVariable("id") String id) {
model.addAttribute("id", id);
model.addAttribute("item", new Item());
if (Integer.parseInt(id) != 0) {
model.addAttribute("edit", true);
} else {
model.addAttribute("edit", false);
}
System.out.println(model.toString());
return "item";
}
which determines if it is an add/ edit call and accordingly sets the value of booleanedit.
Below given is my item.jsp page.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<script type="text/javascript">
var itemurl = "";
function onDelete(event) {
var doDelete = confirm("Are you sure you want to delete this offer?");
if (doDelete == false) {
event.preventDefault();
}
}
function onReady() {
$("#delete").click(onDelete);
}
$(document).ready(onReady);
function updateItemDetails(item) {
$("#itemName").val(item.itemName);
$("#taxPercentage").val(item.taxPercentage);
$("#price").val(item.price);
$("#count").val(item.count);
}
function updatePage(itemurl) {
$.getJSON("<c:url value='${itemurl}'/>", updateItemDetails);
}
</script>
<c:if test="${edit}">
<c:set var="itemurl" value="/getitem/${id}"></c:set>
<c:out value="${itemurl}" />
<script type="text/javascript">
updatePage(itemurl);
</script>
</c:if>
<sf:form method="put"
action="${pageContext.request.contextPath}/saveitem" commandName="item">
<sf:input type="hidden" name="itemId" path="itemId" />
<table class="formtable">
<tr>
<td class="label">Item Name :</td>
<td><sf:input class="control" path="itemName" name="itemName"
id="itemName" type="text" />
<div class="error">
<sf:errors path="itemName"></sf:errors>
</div></td>
</tr>
<tr>
<td class="label">Tax Percentage :</td>
<td><sf:input class="control" path="taxPercentage"
name="taxPercentage" id="taxPercentage" type="text" />
<div class="error">
<sf:errors path="taxPercentage"></sf:errors>
</div></td>
</tr>
<tr>
<td class="label">Price :</td>
<td><sf:input class="control" path="price" name="price"
id="price" type="text" />
<div class="error">
<sf:errors path="price"></sf:errors>
</div></td>
</tr>
<tr>
<td class="label">Count :</td>
<td><sf:input class="control" path="count" name="count"
id="count" type="text" />
<div class="error">
<sf:errors path="count"></sf:errors>
</div></td>
</tr>
<tr align="center">
<td colspan="2"><input class="control" value="Save offer"
type="submit" /> <c:if test="${item.itemId != 0}">
<input name="delete" class="control" value="Remove offer"
type="submit" id="delete" />
</c:if></td>
</tr>
</table>
</sf:form>
Above the form I have added a <c:out> to see what url is being formed.
The rest method being used is,
#RequestMapping(value = "/getitem/{id}", method = RequestMethod.GET, produces="application/json")
#ResponseBody
public Item getItem(#PathVariable("id") String id) {
Item item = itemsService.getItem(Integer.parseInt(id));
return item;
}
The issue is that, if i make a url request with a particular id, in the <c:out value="${itemurl}" /> the correct url is shown, but the form is poulated with item details from the previous url request.
What could be the reason? Could you point out what i'm doing wrong here?
I try to get selected values of checkboxlist.I wanna send values to UrunList action.Each values will be saved in Viewbag.abc then Viewbag will be sent Create view (another view).But I can't get values from checkboxlist with javascript
Script
<script>
$(document).ready(function ()
{
$('#urunsec').change(function () {
var id=$('#urunsec').value();
$ajax({
url:'Fatura/UrunList',
type:'POST',
data: { id: id },
success: function () {
alert('suc');
},
error: function (error) {
alert('error')
}
})
});
});
UrunList View
#foreach (BillApplication.Models.Urunler con in Model )
{
<tr>
<td>
<input id="urunsec" type="checkbox" name="urunsec" value="#con.UrunId.ToString()" />
<input name="urunsec" type="hidden" value="false" />
</td>
<td>#con.UrunId</td>
<td>#con.UrunAdi</td>
<td>#con.UrunFiyat</td>
<td>#con.AltkategoriId</td>
<td colspan="4"></td>
</tr>
}
<tr>
<td>
<input id="Button1" type="button" value="button" onclick="location.href = '#Url.Action("Create", new { idlist= #ViewBag.abc as List<String>})'" />
</td>
</tr>
UrunList Action
[HttpPost]
public ActionResult UrunList(string id)
{
this.UrunList(id);
List<String> idlist = new List<String>();
idlist.Add(id);
ViewBag.abc= idlist;
return RedirectToAction("Create");
}
Create View
<td><textarea id="txt_urunler" rows="2" cols="20" style="border-style:inset; width:150px; border-width:0.2em; border-color:gainsboro">
#if (#ViewBag.abc != null)
{
foreach (var i in ViewBag.abc)
{
#i
}
}
</textarea>
</td>
Create Action
public ActionResult Create(List<String> idlist)
{
string virgul = ",";
ViewBag.virgul = virgul;
if (idlist != null)
{
ViewBag.abc = idlist;
}
return View();
}
The same id may be a cause of this issue. You should try to assign different id (some unique value) to each element or you can try this:-
#foreach (BillApplication.Models.Urunler con in Model )
{
<tr>
<td>
<input type="checkbox" name="urunsec" value="#con.UrunId.ToString()" onclick="ClickMe(this);" />
<input name="urunsec" type="hidden" value="false" />
</td>
<td>#con.UrunId</td>
<td>#con.UrunAdi</td>
<td>#con.UrunFiyat</td>
<td>#con.AltkategoriId</td>
<td colspan="4"></td>
</tr>
}
<tr>
<td>
<input id="Button1" type="button" value="button" onclick="location.href = '#Url.Action("Create", new { idlist= #ViewBag.abc as List<String>})'" />
</td>
</tr>
<script>
function ClickMe(ref) {
var id=$(ref).value();
$.ajax({
url:'Fatura/UrunList',
type:'POST',
data: { id: id },
success: function () {
alert('suc');
},
error: function (error) {
alert('error')
}
})
}
</script>
This should work with your case.