Is't possible to get access to <ul> and <li> during submiting form - asp.net-mvc-3

I have view with controller. I would like to know if it is possible to get access to ul and li? I don't want to do ajax call and pass these elements as parameters. Li elements are added on client side dynamically. this.Request.Form show me only 'name' variable without 'list'. Any advices?
<form action="#Url.Action("Filter")" method="POST">
<ul data-role="listview" data-inset="true" data-filter="false" name="list">
#foreach (var item in #Model.Items)
{
<li value="#item">#item</li>
}
</ul>
<input type="text" name="name"/>
<inpu type="submit" value="Filter"/>
</form>
and controller:
[HttpPost]
public ActionResult Filter(string name, List<string> list)
{
// working with list
return RedirectToAction("Index");
}
thanks

No,
It is not possible to access <ul> and <li> on post back.
BTW, the following code is generates <li> on server not on client
#foreach (var item in #Model.Items)
{
<li value="#item">#item</li>
}
If you wish to access Items (#item) on server, there are other ways to get those that do not require access to <ul> or <li>
For instance, you can emit a hidden (#Html.HiddenFor) element in each <li> in your loop.

You can try the following.
I'm not sure what your view model looks like, but it seems like a list of string values? So then it will look like this in your view model:
public class YourViewModel
{
public List<string> Items { get; set; }
}
In your view try the following:
<ul>
#for (int i = 0; i < Model.Items.Count(); i++)
{
<li>
#Html.DisplayFor(x => x.Items[i])
#Html.HiddenFor(x => x.Items[i])
</li>
}
</ul>
When you post then these items should still be in the list.
It might not be a perfect solution but it can guide you on the right track.
I hope this helps.

Related

View data from another controller in ASP.NET Core MVC

I'm trying to build an ASP.NET Core 6 MVC app.
I have two controllers 'home' and 'work'. How can I display data from 'work' model in the home/index view?
Unfortunately, I don't know the terminology to better formulate the question, but actually I want to achieve that on the home page I can display the last few works.
The part where I enter/edit data works fine. When I go to the /Works/Index page, I see all the entered data. How to display, for example, the last 4 on the home page of the application
In index.cshtml I have
#model IEnumerable<Website.Models.Work>
#foreach (var item in Model)
{
<div class="col-lg-3 col-sm-6">
<div class="gallery-item wow fadeInUp delay-0-2s">
<img src="~/assets/images/gallery/gallery-1.jpg" alt="Gallery">
<div class="gallery-content">
<span class="category">#Html.DisplayFor(modelItem => item.Tag)</span>
<h5>#Html.DisplayFor(modelItem => item.Headline)</h5>
</div>
</div>
</div>
}
But I get an error:
System.NullReferenceException: Object reference not set to an instance of an object.
If you just want to know how to display the data on page, here is a working demo below:
HomeController
public class HomeController: Controller
{
private readonly YourDbContext _context;
public HomeController(YourDbContext context)
{
_context = context;
}
public IActionResult Index()
{
//get the last 4 records...
var model = _context.Work.AsEnumerable().Reverse().Take(4).ToList();
return View(model);
}
}
Home/Index.cshtml
#model IEnumerable<Website.Models.Work>
#foreach (var item in Model)
{
<div class="col-lg-3 col-sm-6">
<div class="gallery-item wow fadeInUp delay-0-2s">
<img src="~/assets/images/gallery/gallery-1.jpg" alt="Gallery">
<div class="gallery-content">
<span class="category">#Html.DisplayFor(modelItem => item.Tag)</span>
<h5>#Html.DisplayFor(modelItem => item.Headline)</h5>
</div>
</div>
</div>
}

Implement pagination in JSP page in a Spring MVC and Hibernate application

I am trying to implement pagination in my JSP page. I am using Spring MVC and Hibernate. The java code part is okay but I am having difficulties implementing it in my JSP page. I am using twitter bootstrap.
Here is what I did until now:
<div class="container">
<table class="table table-hover">
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
<c:forEach items="${employees}" var="emp">
<tr>
<td>${emp.firstName}</td>
<td>${emp.lastName}</td>
<td>${emp.Age}</td>
</tr>
</c:forEach>
</table>
<div class="pagination">
<ul>
<li class="disabled">First</li>
<li class="disabled">Prev</li>
<li class="active">1</li>
<li class="active">2</li>
<li class="active">3</li>
<li class="active">4</li>
<li class="active">5</li>
<li class="active">Next</li>
<li class="active">Last</li>
</ul>
</div>
</div>
This is the related code in my controller:
#RequestMapping(value = "/list", method = RequestMethod.GET)
public String getEmployees(ModelMap model) {
**//I believe I should get the page number from the JSP here but how?**
model.addAttribute("employees", this.employeeService.getEmployees(page));
return "listing";
}
This is the related code in my Service class:
public List<Employee> getEmployees(int page) {
return employeeDao.getEmployeeList(page);
}
This is the related code in my DAO class:
private static final int limitResultsPerPage = 3;
public List<Employee> getEmployeeList(int page) {
Query q = sessionFactory.getCurrentSession().createQuery(
"from Employee");
q.setFirstResult(page * limitResultsPerPage);
q.setMaxResults(limitResultsPerPage);
return (List<Employee>) q.list();
}
The page where I am displaying that table is list.jsp
Here are my assumptions of what I should do but dont know how (please correct me if I am taking the wrong way):
Modify my link that point to list.jsp in my menu, to list.jsp?page=0, so everytime the user clicks on the link, he will arrive in the first page.
When the user clicks one of the button, I need to pass the page number to my controller so I can manage to return the right "employees" with my query.
As you can see, the First and Previous buttons are deactivated as I am currently on the first page. So my question is, how should I handle the activation/deactivation of those buttons, as well as the Next and Last ones?
Also, how to "refresh" the numbers on the list? For example, if the user is at the page 20, I won't display buttons from 1 to 19?
To answer one of your questions at least:
You can pass the page number and other parameters from the JSP to your controller with the RequestParam annotation like this:
#RequestMapping(value = "/list", method = RequestMethod.GET)
public String getEmployees(#RequestParam(value = "page", required = false) Long page, ModelMap model) {
//now page is available.
model.addAttribute("employees", this.employeeService.getEmployees(page));
return "listing";
}
And your link will look something like this:
list/?page=1
Pagination is a fairly complicated process but here are a few ideas. You can use JSTL on the JSP page to implement the logic. For instance:
<c:if test="${page > 1}">
<li class="active">First</li>
</c:if>
I suggest that you do some calculations in the Action for the number of pages that you want to display. Say for instance that you always want to display ten links. On page 1, you will display pages 1...10, on page 7 you will display pages 2...12 and so on. In the action you can determine the starting page and the ending page to display.
int startpage = page - 5 > 0?page - 5:1;
int endpage = startpage + 10;
On the JSP page you can do a loop maybe:
<c:forEach begin="${startpage}" end="${endpage}" var="p">
${p}
</c:forEach>
and so on.
Vincent Ramdhanie solution is correct: thanks for that. Dukable: I used this code based on Vincent Ramdhanie's solution and it works really well: something like this should work in your code.
#RequestMapping(value = "/list", method = RequestMethod.GET)
public String getEmployees(#RequestParam(value = "page", required = false) Long page, ModelMap model) {
//now page is available.
int startpage = (int) (page - 5 > 0?page - 5:1);
int endpage = startpage + 10;
model.addAttribute("employees", this.employeeService.getEmployees(page));
model.addAttribute("startpage",startpage);
model.addAttribute("endpage",endpage);
return "listing";
}
And in your jsp:
<div class="pagination">
<ul>
<li><c:forEach begin="${startpage}" end="${endpage}" var="p">${p}</c:forEach></li>
</ul>
</div>
You can access to your jsp on this way:
http://localhost:8080/Project/list/?page=1
`<div class="box-tools pull-right">
<ul class="pagination pagination-sm inline">
<c:if test="${pageCtn gt 1}">
<li>
<c:choose>
<c:when test="${currentPage gt 1}">
«
</c:when>
<c:otherwise>
<a>«</a>
</c:otherwise>
</c:choose>
</li>
<li>${currentPage} to ${pageCtn}</li>
<li>
<c:choose>
<c:when test="${currentPage lt pageCtn}">
»
</c:when>
<c:otherwise>
<a>»</a>
</c:otherwise>
</c:choose>
</li>
</c:if>
</ul>
</div>`

How to use inline template with multiple inputs in MVC Razor view

Inside my view I currently have
#{
Func<Website.Security.User[], object> renderUserList = #<text>
<div class="span4">
#*<h2>#title</h2>*#
<ul>
#foreach (var user in item)
{
<li>#user.UserName - Edit</li>
}
</ul>
</div>
</text>;
}
#renderUserList(Model.AdminUsers)
How can I rework this so that the renderUserList expression can take in a second input for the section title?
As I understand, you trying to create helper: ASP.NET MVC 3 and the #helper syntax within Razor
#helper renderUserList(Website.Security.User[] users, string title)
{
<div class="span4">
<h2>#title</h2>
<ul>
#foreach (var user in users)
{
<li>#user.UserName - Edit</li>
}
</ul>
</div>
}

Razor Syntax Not working the way I expected

having some trouble with my razor syntax
gives a Parsor error saying that
The foreach block is missing a closing "}" character
<ul>
#{var client = "null";}
#foreach (var instance in Model)
{
if (instance.tbl_Policy.tbl_Client.txt_clientName != client)
{
client = instance.tbl_Policy.tbl_Client.txt_clientName;
</ul><h1>#client</h1>
<ul>
}
<li>
#instance.tbl_Policy.txt_policyNumber -
Assigned to : #instance.aspnet_Membership.aspnet_User.UserName
#instance.ATLCheckType.Question
<button type="button" rel="<%:instance.ATLCheckInstanceId.ToString()%>">DelFiled</button>
<button type="button" rel="<%:instance.ATLCheckInstanceId.ToString()%>">DelLineItem</button>
</li>
}
</ul>
Razor cannot handle imbalanced HTML tags in code blocks.
Change your if block to treat the imbalanced tags as plain text:
if (instance.tbl_Policy.tbl_Client.txt_clientName != client)
{
client = instance.tbl_Policy.tbl_Client.txt_clientName;
#:</ul><h1>#client</h1>
#:<ul>
}
The code should be refactored to correctly support balanced tags
#foreach (var groupedClient in Model.GroupBy(i => i.tbl_Policy.tbl_Client.txt_clientName))
{
<ul>
<h1>#groupedClient.Key</h1>
foreach(var instance in groupedClient)
{
<li>
#instance.tbl_Policy.txt_policyNumber -
Assigned to : #instance.aspnet_Membership.aspnet_User.UserName
#instance.ATLCheckType.Question
<button type="button" rel="#instance.ATLCheckInstanceId.ToString()">DelFiled</button>
<button type="button" rel="#instance.ATLCheckInstanceId.ToString()">DelLineItem</button>
</li>
}
</ul>
}
What's with all of the <%: %> stuff in there? You need to use the # syntax.
<ul>
#{var client = "null";}
#foreach (var instance in Model)
{
if (instance.tbl_Policy.tbl_Client.txt_clientName != client)
{
client = instance.tbl_Policy.tbl_Client.txt_clientName;
</ul><h1>#client</h1>
<ul>
}
<li>
#instance.tbl_Policy.txt_policyNumber -
Assigned to : #instance.aspnet_Membership.aspnet_User.UserName
#instance.ATLCheckType.Question
<button type="button" rel="#instance.ATLCheckInstanceId.ToString()">DelFiled</button>
<button type="button" rel="#instance.ATLCheckInstanceId.ToString()">DelLineItem</button>
</li>
}
</ul>

Request.Forms.Keys.Count = 0 on Postback

I have the following HTML on my displayed form
<fieldset>
<legend>Edit User Roles</legend>
<ul>
<% foreach (string role in (string[]) ViewData["roles"]){ %>
<li>
<div id="Div4" class="grid_6">
<div id="Div5" class="grid_2 alpha" style="font-weight: bold;">
<%= Html.CheckBox("role." + role, Roles.IsUserInRole(Model.UserName, role))%>
</div>
<div id="Div6" class="grid_3 omega" style="font-family: Verdana; font-size: 10pt;">
<label for="role.<%: role %>">
<%: role %></label><br />
</div>
</div>
</li>
<% } %>
</ul>
</fieldset>
I have the following code in my Controller
[HttpPost]
public ActionResult EditUser( string id, bool approved )
{
int i = Request.Form.Keys.Count
foreach (string key in Request.Form.Keys)
{
if (key.StartsWith( "role." ))
{
// Do something
}
}
MembershipUser membershipUser = Membership.GetUser( id );
return View( membershipUser );
}
If I break the code and explore, I find that the Request.Form.Keys.Count = 0, although there should be at least 4 keys created with "role." as a prefix from four checkboxes displayed on the form.
What am I not understanding here?
Request.Form.Keys.Count = 0 could have two possible explanations:
No value was sent in the POST body
You used some special content type such as for example application/json instead of application/x-www-form-urlencoded (could happen if you play with AJAX)
I would recommend you using FireBug to see exactly what's contained in the POST request and if there are any values. You haven't shown the form definition neither how you are submitting it. If you are POSTing with AJAX maybe there's where the problem lies.
Here's an example of how a valid request might look like in FireBug:

Resources