I am a beginner in ASP.Net MVC 3
I will make a dynamic array initially must show me the first ten elements, and when I click view more displays all array elements
here's what I did:
<table>
#foreach (var tweet in Model)
{
<tr>
<td>
<img alt="" src="#tweet.ProfileImageUrl" />
<br />
<input id="rowIDs" type="checkbox" />
</td>
<td>
<strong>#tweet.Name</strong>
<br />
Friends: <strong>#tweet.FriendsCount</strong>
</td>
</tr>
}
</table>
thank you in advance
You have to put 10 items in the controller,
return View(array.Take(10).Skip(page));
Do not use the button anymore. Use the pager.
You need to peredovat variable Pag.
The easiest way(on my opinion) is to create a anchor to the page, itself, with a query string.
Your View must have an anchor like this:
All Comments
And relative controller(HttpGet, not HttpPost(if it has any)) must be something like this:
public ViewResult List(bool fullComment=false)
{
if (fullComment)
return View(dbContext.EntityList.ToList());
else
return View(dbContext.EntityList.Take(5).ToList());
}
Note: if the page has querystring already, in creating anchor link, in view, you must pay attention to this.
Related
I am listing objects in a table in my view. I want to be able to edit an object using a button in the table.
<#list products as product>
<tr>
<td>${product.productName}</td>
<td>${product.price}</td>
<td>${product.quantity}</td>
<td>
<form name="product" method="post" action="/product/edit">
<input type="submit" name="submit" value="Edit this product"/>
</form>
</td>
</tr>
</#list>
The object then should be passed to a controller method:
#RequestMapping(value="/edit", method = RequestMethod.POST)
public ModelAndView edit(#ModelAttribute("product") Product product){
ModelAndView mav = new ModelAndView("product/edit");
mav.addObject("product", product);
return mav;
}
However, the product obtained by the edit method is null. How do I fix this? I tried to bind the product inside form using the code below, but that did not work either.
<form name="product" method="post" action="/product/edit">
<#spring.bind "product" />
<input type="hidden" name="${spring.status.expression}" value="${spring.status.value}"/>
<input type="submit" name="submit" value="Edit this product"/>
</form>
I want to use the POST method.
I would like to suggest a different approach. If I'm not mistaken you just want to pick an object for later editing - you don't really edit it in that very view.
If so, all you have to do is to pass an identifier of your object to your controller, but not the selected object itself.
If not, you should give us the hole story and provide the rest of the view as well.
Assuming I'm right the next question is why you need to use a form submission at all. Passing an id is best done by links - either as parameter or, if you follow REST-style, as part of the URI itself:
<!-- Link parameter -->
<#list products as product>
<tr>
<td>${product.productName}</td>
<td>${product.price}</td>
<td>${product.quantity}</td>
<td>
Edit ${product.productName}
</td>
</tr>
</#list>
<!-- REST-style -->
...
Edit ${product.productName}
...
productName isn't a good id of course. If products is a list (meaning, java.util.List) the index of the list is handy. Even in a HashMap or Set I'd create a unique id instead of using the product name.
Now that you can identify your object, select it in the backing code for later editing, but not in the view.
You'll find loads of examples of how to get link parameters in a controller. So, no need to go into detail here.
If however you insist on using a form and a POST-method then do it like this:
<form method="post" action="/product/edit">
<#list products as product>
<tr>
<td>${product.productName}</td>
<td>${product.price}</td>
<td>${product.quantity}</td>
<td>
<button value="${product.productName}" name="product" type="submit">Edit ${product.productName}</button>
</td>
</tr>
</#list>
</form>
Note that this won't work for older IE browsers (below Ver. 10), because they don't return the value, but everything that is inside the button tag.
Hidden inputs and a single submit button won't help at all, because all inputs are submitted and using different forms is not the way either.
I have an image tag in a database field which I want to show the image in the index and detail views within an MVC project. Currently the both pages just show the text
The view code for that field is:
<td>
#Html.DisplayFor(modelItem => item.QRCode)
</td>
How to to code the view pages to show the image the link points to rather than the link text?
Cheers,
Kevin.
According to this link : displaying image from db in Razor/MVC3
Two possibilities.
Write a controller action instead which given an image id will return this image:
public ActionResult GetImage(int id)
{
byte[] image = ... go and fetch the image buffer from the database given the id
return File(image, "image/jpg");
}
and then:
<img src="#Url.Action("GetImage", "SomeController", new { id = item.Id })" alt="#item.CountryName" />
Obviously now in your initial model you don't need the Image property. This will be retrieved subsequently in the controller action responsible for that.
Another possibility is to use data URI scheme to embed the images as base64 strings but it might not be widely supported by all browsers:
<img src="data:image/jpg;base64,#(Convert.ToBase64String(item.Image))" alt="#item.CountryName" />
You don't need a controller action in this case as the images are directly embedded into your markup as base64 strings.
Happy Coding..!!
The following code works for the index view:
<td>
<img src="#Url.Content(item.QRCode)" alt="Image" />
</td>
Thanks for the help.
The problem I now have is getting the image to show in the details page. The code I have tried is:
<dd>
<img src=#Model.QRCode alt="" />
</dd>
The other columns that work on the details page use:
<dd>
#Html.DisplayFor(model => model.TestingFrequency)
</dd>
But I have tried many combinations of code and I can't seem to get it to work.
Any further tips would be appreciated.
I am trying to create an order form for input.
I need the user to be able to add multiple line items then update. I was trying to
use the shopping cart class (where user creates a cart item and adds a
list item, multiple lines can be added to the list item).
I didn't get through with that. I am using asp.net razor am using
webmatrix to build site. Webmatrix is saying that it doesnt recognise Cart().
#{
if (Session["cart"] == null)
{
Session["cart"] = new Cart();
}
Cart cart = (Cart)Session["cart"];
}
<table id="cartTable">
<tr>
<th class="product">Product</th>
<th class="size">Size</th>
<th class="price">Price</th>
</tr>
#foreach (var item in cart.Items)
{
<tr>
<td class="product">#item.ProductID</td>
<td class="size">#item.Size</td>
<td class="price">£#item.Price</td>
</tr>
}
</table>
Is there a better way to do this? All help is greatly appreciated
There IS a way to bind dynamic list elements
#foreach (i=0; i< cart.Items.count; i++)
{
<tr>
<td class="product"> <input type="hidden" name="cart.item[#i].ProductID"> </td>
<td class="size"> <input type="text" name="cart.item[#i].Size"> </td>
<td class="price">£ <input type="text" name="cart.item[#i].Price"> </td>
</tr>
}
Webmatrix is saying that it doesnt recognise Cart()
I strongly recommend you place your Models in the Models folder and make them part of the Models namespace. Then they should be available automatically. Otherwise, you may have to reference cart by it's complete reference path (if it is not in your Models folder). example
Datalayer.Entities.Cart cart = (Datalayer.Entities.Cart)Session["cart"];
Final Note:
You are not passing your Cart as a Model to your View
example
#model {Project}.Entities.Cart
This is a better practice using the MVC 3 framework. You would have discovered whatever reference problem earlier and would have the option to use tightly bound Helpers
I recommend using the Visual Studio 2012 Express over WebMatrix for MVC development. Furthermore, I would also suggest using jQuery (javascript) if you wish to let users add line items on the fly via the same page. I can share an example with you if you like.
One more note: You tagged this with both MVC and WebForms, which are two very different platforms.
Edit:
I think Dave A's solution may be better, but to do this with jQuery:
1 Put your add button and hidden div in a form
<form action="/MyController/MyAction" method="post" id="addListItemForm">
<button id="addListItemButton">Add List Item</button>
<div style="hidden">
<input type="text" name="product" id="product" />
<button id="addButton">Add</button>
</div>
<input type="submit" text="Submit" />
</form>
2 Show the form fields on button click
$('#addListItemButton').click(function(){
$('#addListItemForm div').show();
});
3 Add hidden field on add button click
$('#addButton').click(function(){
var product = $('#addListItemForm #product').val();
$("input").attr({
name : "productListItems[]",
type : "hidden",
value : product
}).after('#addListItemForm');
});
4 When the form submits, you will have various product names in the productListItems array passed via POST method.
Note: You'll have to play with this a little bit, but it would be a good learning exercise... I am not exactly sure what you are trying to do, but this is my best guess.
I am trying to use knockout.js to show a specification object on the UI. The specification has a name and it has a few parameterInfo rows. Each ParameterInfo row has a ParameterPartNumber and a bunch of SignalInputs. Each SignalInput has just one property called Name. I am able to show the specification name, the parameterInfo rows and ParameterPartNumber but am not able to show the bunch of SignalInput Names that I have even though the SpecificationModel has the values. I am using the following code:
HTML code:
<div id="specificationHeader">
Name : <input data-bind='value: Name' />
<br />
<br />
</div>
<table>
<thead>
<tr>
<th>
Parameter Part
</th>
<th>
Signal Inputs
</th>
</tr>
</thead>
<tbody data-bind="foreach: ParameterInfos">
<tr>
<td>
<input data-bind='value: ParameterPartNumber' />
</td>
<td>
<ul data-bind="foreach: SignalInputs">
<li><span data-bind='text: Name' /></li>
</ul>
</td>
</tr>
</tbody>
</table>
Javascript/Knockout code:
<script type="text/javascript">
var SpecificationModel = function (specification) {
var self = this;
self.Name = ko.observable(specification.Name);
self.ParameterInfos = ko.observableArray(ko.utils.arrayMap(specification.ParameterInfos, function (ParameterInfo) {
return { ParameterPartNumber: ParameterInfo.ParameterPartNumber, SignalInputs: ko.observableArray(ParameterInfo.SignalInputs) };
}));
};
var specificationData = '#Html.Raw(ViewBag.SpecificationData)';
var viewModel = new SpecificationModel($.parseJSON(specificationData))
ko.applyBindings(viewModel);
</script>
When I run the program in debug mode, I can see the following values:
var specificationData = '{"Name":"Specification One",
"ParameterInfos": [{"ParameterPartNumber":"26-20700-002", "SignalInputs":[{"Name":"Park Brake"},{"Name":"Neutral"}]} ]}';
It's strange because I was able to get an almost similar example working thanks to the answers for the following question:
Need to pass initial viewmodel data from ASP.NET MVC to knockout.js
Still, somehow the binding code is not working. What am I missing?
EDIT:
Ok, the following lines work:
<td data-bind="foreach: SignalInputs">
<ul >
<li><span data-bind='text: Name' /></li>
</ul>
</td>
But, the following lines don't
<td>
<ul data-bind="foreach: SignalInputs">
<li><span data-bind='text: Name' /></li>
</ul>
</td>
Any idea why? The latter site of lines work in the other stackoverflow example question I cited.
In my experience when you run into weird binding errors, it often stems from the for-each binding. Because I've had so many issues with it, I pretty much just go the "containerless" route:
<!-- ko foreach: myItems -->
<li>Item <span data-bind="text: $data"></span></li>
<!-- /ko -->
I was having problems binding, but my issue turned out to be because I was using an early version of (knockout 1.2.1) that didn't support the foreach binding. It didn't throw an error for an unrecognised binding function though, just when I tried to reference an element within the collection I was supposedly binding to making it hard to debug.
In the end I used a template binding as per the answer here: Stackoverflow: knockout javascript foreach binding
I remember reading in the KnockoutJS documentation that the bindings run into issues with empty elements like <span .... /> and they suggest using <span ...></span> or even <span ...> </span> (the latter being a countermeasure to an IE6 bug).
Not sure this is relevant since this answer was posted so long ago but I was having an issue with foreach as well. I noticed that the error was coming from a jquery call in knockout (i was using knockout-2.0.0) and jquery-2.1.1. When I updated to knockout-3.1.0, this problem was solved.
2.0.0 was installed when I installed knockout.mapping via nuget and it probably depends on 2.0.0 at least. Hope this helps someone...
I'm trying to access the values a user introduces in a table from my controller.
This table is NOT part of the model, and the view source code is something like:
<table id="tableSeriales" summary="Seriales" class="servicesT" cellspacing="0" style="width: 100%">
<tr>
<td class="servHd">Seriales</td>
</tr>
<tr id="t0">
<td class="servBodL">
<input id="0" type="text" value="1234" onkeypress = "return handleKeyPress(event, this.id);"/>
<input id="1" type="text" value="578" onkeypress = "return handleKeyPress(event, this.id);"/>
.
.
.
</td>
</tr>
</table>
How can I get those values (1234, 578) from the controller?
Receiving a formcollection doesn't work since it does not get the table...
Thank you.
Using the FormCollection should work unless your table is not inside of a <form> tag
On top of Lazarus's comment, you can try this, but you have to set the name attribute for each:
<input id="seriales[0]" name="seriales[0]" type="text" value="1234" onkeypress="return handleKeyPress(event, this.id);"/>
<input id="seriales[1]" name="seriales[1]" type="text" value="578" onkeypress="return handleKeyPress(event, this.id);"/>
Now in your Action method you can make your method look like this:
[HttpPost]
public ActionResult MyMethod(IList<int> seriales)
{
// seriales.Count() == 2
// seriales[0] == 1234
// seriales[1] == 578
return View();
}
and seriales will be wired up to those values.
First Option:
Using FormCollection is the simplest way to access dynamic data. It is strange that you cannot get those values from it, can you check the following?
Is the table inside the
element?
Can you add name attribute
to the input elements? Note that
form items are bound by their names,
not id.
Second Option:
The second option is to add a collection in your model, and name everything accordingly. i.e.
public class MyModel
{
...
public IList<string> MyTableItems { get; set; }
}
and in your view use following names:
<input name="MyTableItems[]" value="" />