I want to be able to upload a file then to download it or delete it. But when I try to delete it, I get this error:
The view 'Delete' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/FileUpload/Delete.aspx ,~/Views/FileUpload/Delete.ascx, ~/Views/Shared/Delete.aspx,~/Views/Shared/Delete.ascx, ~/Views/FileUpload/Delete.cshtml, ~/Views/FileUpload/Delete.vbhtml, ~/Views/Shared/Delete.cshtml ,~/Views/Shared/Delete.vbhtml .
[HttpGet]
public ActionResult Delete( string deletedfile)
{
string current_usr = User.Identity.GetUserId();
string fullPath = Request.MapPath("~/Files/" + current_usr + "/" + deletedfile);
if (System.IO.File.Exists(fullPath))
{
System.IO.File.Delete(fullPath);
ViewBag.Message="Deleted";
}
var items = GetFiles();
return View(items);
}
// GET: FileUpload
public ActionResult Index()
{
var items = GetFiles();
return View(items);
}
// POST: FileUpload
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
try
{
string current_usr = User.Identity.GetUserId();
//string path = Path.Combine(Server.MapPath("~/Files/"),
// Path.GetFileName(file.FileName));
var folder = Server.MapPath("~/Files/" + current_usr + "/");
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
string path = Path.Combine(String.Format(folder),
Path.GetFileName(file.FileName));
file.SaveAs(path);
ViewBag.Message = "File uploaded successfully";
}
catch (Exception ex)
{
ViewBag.Message = "ERROR:" + ex.Message.ToString();
}
else
{
ViewBag.Message = "You have not specified a file.";
}
var items = GetFiles();
return View(items);
}
public FileResult Download(string downloadedfile)
{
string current_usr = User.Identity.GetUserId();
var FileVirtualPath = "~/Files/" + current_usr + "/" + downloadedfile;
return File(FileVirtualPath, "application/force-download", Path.GetFileName(FileVirtualPath));
}
private List<string> GetFiles()
{
string current_usr = User.Identity.GetUserId();
var dir = new System.IO.DirectoryInfo(Server.MapPath("~/Files/" + current_usr + "/"));
System.IO.FileInfo[] fileNames = dir.GetFiles("*.*");
List<string> items = new List<string>();
foreach (var file in fileNames)
{
items.Add(file.Name);
}
return items;
}
The View :
<h2> File Upload </h2>
#model List<string>
#using (Html.BeginForm("Index", "FileUpload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<label for="file"> Upload </label>
<input type="file" name="file" id="file" />
<br /><br />
<input type="submit" value="Upload" />
<br /><br />
#ViewBag.Message
<br />
<h2>Documents list</h2>
<table style="width:100%">
<tr>
<th> File Name </th>
<th> Link </th>
</tr>
#for (var i = 0; i <= (Model.Count) - 1; i++)
{
<tr>
<td>#Model[i].ToString() </td>
<td>#Html.ActionLink("Download", "Download", new { downloadedfile = Model[i].ToString() }) </td>
<td>
#Html.ActionLink("Delete", "Delete", new { deletedfile = Model[i].ToString() })
</td>
</tr>
}
</table>
}
The issue is that your Delete Controller method is calling View() at the end. That method will attempt to find a view file with the name of the controller method. If you want to show the list of files after the delete you can redirect to your index action like this:
[HttpGet]
public ActionResult Delete(string deletedfile)
{
string current_usr = User.Identity.GetUserId();
string fullPath = Request.MapPath("~/Files/" + current_usr + "/" + deletedfile);
if (System.IO.File.Exists(fullPath))
{
System.IO.File.Delete(fullPath);
ViewBag.Message = "Deleted";
}
return RedirectToAction("Index");
}
See this link from the microsoft Docs for more detail on redirecting
https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/views/asp-net-mvc-views-overview-cs
my job consists in recovering from a web service a form already filled; modify it with the transmit, the problem that the loop that I made gets the model before the modification I want to know how to recover the form after the modification
List<ModeleForm> modeles = new ArrayList<ModeleForm>();
for (DynaFormControl dynaFormControl : model.getControls()) {
System.out.println("recup");
modeles.add((ModeleForm) dynaFormControl.getData());
}
I tried this loop but it retrieves only the initial values.
model = new DynaFormModel();
try {
String url = "http://localhost:8080/activiti-rest/service/form/form-data?taskId=" + idTask + "";
Representation respons = getClientResource(url).get(MediaType.APPLICATION_JSON);
JSONObject object = new JSONObject(respons.getText());
if (object != null) {
JSONArray formProperties = object.getJSONArray("formProperties");
DynaFormLabel labels[] = new DynaFormLabel[0];
DynaFormControl labels2[] = new DynaFormControl[0];
labels = new DynaFormLabel[formProperties.length()];
labels2 = new DynaFormControl[formProperties.length()];
for (int i = 0; i < (formProperties.length()); i++) {
DynaFormRow row = model.createRegularRow();
boolean required = Boolean.valueOf(formProperties.getJSONObject(i).getString("required"));
labels[i] = row.addLabel(formProperties.getJSONObject(i).getString("name"));
labels2[i] = row.addControl(new ModeleForm(formProperties.getJSONObject(i).getString("name"), formProperties.getJSONObject(i).getString("id"), formProperties.getJSONObject(i).getString("value"), required), getType(formProperties.getJSONObject(i).getString("type")));
labels[i].setForControl(labels2[i]);
}
labels = null;
labels2 = null;
}
object = null;
} catch (MalformedURLException ex) {
Logger.getLogger(DemandeGeneraleController.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(DemandeGeneraleController.class.getName()).log(Level.SEVERE, null, ex);
} catch (JSONException ex) {
Logger.getLogger(DemandeGeneraleController.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("apres la fct create");
return model;
}
this code create the modele
<h:panelGroup id="dynaFormGroup">
<pe:dynaForm id="dynaForm" value="#{tachesController.createForm()}" var="data"
autoSubmit="true" widgetVar="dynaForm" >
<ui:include src="colsAddM2.xhtml"/>
</pe:dynaForm>
</h:panelGroup>
my page .xhtml which displays the dynamic form
I would like to add filter for JSF table and limit the values based on filter value.
<h:inputText id="search" value="#{accounts.searchString}"></h:inputText>
<h:commandButton value="Search" action="#{accounts.search()}">
<f:ajax execute="search" render="output"></f:ajax>
</h:commandButton>
I suppose that the best way will be to add the filter value into the SQL query:
SELECT * FROM CUSTOMERS ORDER BY %S %S offset ? limit ?
Full code: http://pastebin.com/eEeTWEqK
How I can implement this for the code into the link?
PS. I modified the code this way:
<div class="div_input_style">
<h:inputText id="search" class="input_style" value="#{accounts.searchString}"></h:inputText>
<h:commandButton class="theSpan" value="Search by title">
<f:ajax execute="search" render="output"></f:ajax>
</h:commandButton>
</div>
public List<AccountsObj> list(int firstRow, int rowCount, String sortField, boolean sortAscending) throws SQLException
{
String SqlStatement = null;
if (ds == null)
{
throw new SQLException();
}
Connection conn = ds.getConnection();
if (conn == null)
{
throw new SQLException();
}
String sortDirection = sortAscending ? "ASC" : "DESC";
SqlStatement = "SELECT * FROM ACCOUNT "
+ " WHERE ? IS NULL OR ? IN (USER_NAME, FIRST_NAME, LAST_NAME)"
+ " ORDER BY %S %S offset ? limit ? ";
String sql = String.format(SqlStatement, sortField, sortDirection);
PreparedStatement ps = null;
ResultSet resultSet = null;
List<AccountsObj> resultList = new ArrayList<>();
try
{
conn.setAutoCommit(false);
boolean committed = false;
ps = conn.prepareStatement(sql);
ps.setString(1, searchString);
ps.setString(2, searchString);
ps.setInt(3, firstRow);
ps.setInt(4, rowCount);
resultSet = ps.executeQuery();
resultList = ProcessorArrayList(resultSet);
conn.commit();
committed = true;
}
finally
{
ps.close();
conn.close();
}
return resultList;
}
File: ServiceAnnonce.java
public List<Annonce> loadAnnonce( UserEntity idUser ) {
Query query = getEntityManger().createQuery( "select u from "
+ getPersistentClass().getSimpleName()
+ " u where u.annonceUser= :idUser" ).setParameter( "idUser", idUser );
List<Annonce> annonce = (List) query.getResultList();
return annonce;
}
File : DaoUser.java
public UserEntity loadUserByEmail( String email ) {
Assert.notNull( email );
UserEntity user = null;
Query query = getEntityManger().createQuery( "select u from "
+ getPersistentClass().getSimpleName()
+ " u where u.email= :email" ).setParameter( "email", email );
try {
user = (UserEntity) query.getSingleResult();
} catch ( NoResultException e ) {
}
return user;
}
File : ServiceUser.java
public Annonce annonceEnFonctionId( Annonce annonce, String email ) {
UserEntity user = userDao.loadUserByEmail( email );
List<Annonce> a = annonceDao.loadAnnonce( user );
Annonce an = annonce;
for ( int i = 0; i < a.size(); i++ ) {
if ( a.get( i ).getId() == (Long) an.getId() ) {
an = annonce;
}
}
return an;
}
File: flow.xml
<transition on="annonceID" to="annonceEnFonctionId">
<evaluate expression="userService.annonceEnFonctionId(annonce,user.getEmail())" result="flowScope.annonce" />
</transition>
File : OurAnnonce.java
<p:dataTable var="item" value="#{annonce}">
<p:column style="width:2%">
<h:commandButton value="show" action="annonceID" />
</p:column>
<p:column>
<h:outputText value="#{item.titre}" />
</p:column>
File:shwo.java
<p:dataTable var="valeur" value="#{annonce}">
<p:column headerText="Model">
<h:outputText value="#{valeur.titre}" />
</p:column>
</p:dataTable>
when i click Button show i should get more detail of annonce selected but i still get always the first annonce in DataBase any idea ??
I have some JSF code that currently works (as shown below), and I need to modify it to conditionally suppress the display of certain rows of the table. I know how to conditionally suppress the display of a particular cell, but that seems to create an empty cell, while what I'm trying to do is to not display the row at all.
Any suggestions?
<h:dataTable styleClass="resultsTable" id="t1" value="#{r.common}" var="com" headerClass="headerBackgrnd" rowClasses="rowOdd, rowEven" columnClasses="leftAlign, rightAlign, leftAlign">
<h:column>
<h:outputText rendered="#{com.rendered}" styleClass="inputText" value="#{com.description}: " />
</h:column>
<h:column>
<h:outputText styleClass="outputText" value="#{com.v1}" />
</h:column>
<h:column>
<h:inputText styleClass="inputText" value="#{com.v2}" />
</h:column>
</h:dataTable>
Basically, the line that says #{com.rendered} will conditionally display the contents of a single cell, producing an empty cell when com.rendered is false. But I want to skip an entire row of the display under certain conditions - how would I go about doing that?
Rows correspond to data objects in the collection of your table. If you don't want the row, don't put the object in the collection.
Alternatively, you can use the rowClasses parameter for dataTable.
Bean code:
public String getRowClasses() {
StringBuilder sb = new StringBuilder();
for (Data data : myData) {
sb.append(data.hide ? 'hide,' : 'show,');
}
return sb.toString();
}
CSS:
tr.hide {display:none;}
For people using richFaces, you can use rich:column's filterExpression attribute.
<rich:column filterExpression="#{put your expression here}">
...
</rich>
If the condition is not met, the complete row is filtered out.
Example is using seam EL!
extension to Brian's solution.
To display the column names I did the following in primefaces
<p:dataTable value="#{eiBean.dce.ilDbConns}" var="c">
<p:columnGroup type="header">
<p:row>
<p:column colspan="1" />
<p:column colspan="1" />
</p:row>
<p:row>
<p:column headerText="DataBase Type" width="auto" />
<p:column headerText="URL" width="400" />
</p:row>
</p:columnGroup>
<p:column rendered='#{c.conType == "TARGET"}'>
<p:outputLabel value="#{c.dbType}" />
</p:column>
<p:column rendered='#{c.conType == "TARGET"}'>
<p:outputLabel value="#{c.dbUrl}" />
</p:column>
</p:dataTable>
I extend HtmlTableRenderer default renderer and overwrite renderRowStart method to achieve this by giving style attribute into table->tr element with value display:none.
The item inside binding list needs to implement TableRow interface which only has one method of isHide. In the concrete class you can put any logic you like to give a boolean value.
BTW, in this custom renderer also has PrimeFaces implementation like function which gives the message when table is empty and the table->tr will automatically calculate how many columns in the table and give proper value to colspan attribute.
public class MyDataTableRenderer extends HtmlTableRenderer {
private static final Integer[] ZERO_INT_ARRAY = new Integer[] { 0 };
private static final String NO_RESULT_MESSAGE_ATTR_NAME = "noResultMessage";
private static final String defaultEmptyMessage = "No records found";
private static final Logger log = Logger.getLogger(DHSDataTableRenderer.class.getName());
#Override
public void encodeInnerHtml(FacesContext facesContext, UIComponent component) throws IOException {
UIData uiData = (UIData) component;
String message = (String) uiData.getAttributes().get(NO_RESULT_MESSAGE_ATTR_NAME);
if (message == null || "".equals(message.trim())) {
message = defaultEmptyMessage;
}
ResponseWriter writer = facesContext.getResponseWriter();
int rowCount = uiData.getRowCount();
int newspaperColumns = getNewspaperColumns(component);
int columnNumber = getChildCount(component);
if (rowCount == -1 && newspaperColumns == 1) {
encodeInnerHtmlUnknownRowCount(facesContext, component);
return;
}
if (rowCount == 0) {
// nothing to render, to get valid xhtml we render an empty dummy
// row
writer.startElement(HTML.TBODY_ELEM, uiData);
writer.writeAttribute(HTML.ID_ATTR, component.getClientId(facesContext) + ":tbody_element", null);
writer.startElement(HTML.TR_ELEM, uiData);
writer.startElement(HTML.TD_ELEM, uiData);
writer.writeAttribute(HTML.COLSPAN_ATTR, columnNumber, null);
writer.writeAttribute(HTML.CLASS_ATTR, "dhs-empty-table", null);
writer.write(message);
writer.endElement(HTML.TD_ELEM);
writer.endElement(HTML.TR_ELEM);
writer.endElement(HTML.TBODY_ELEM);
return;
}
// begin the table
// get the CSS styles
Styles styles = getStyles(uiData);
int first = uiData.getFirst();
int rows = uiData.getRows();
int last;
if (rows <= 0) {
last = rowCount;
} else {
last = first + rows;
if (last > rowCount) {
last = rowCount;
}
}
int newspaperRows;
if ((last - first) % newspaperColumns == 0) {
newspaperRows = (last - first) / newspaperColumns;
} else {
newspaperRows = ((last - first) / newspaperColumns) + 1;
}
boolean newspaperHorizontalOrientation = isNewspaperHorizontalOrientation(component);
// get the row indizes for which a new TBODY element should be created
Integer[] bodyrows = getBodyRows(facesContext, component);
int bodyrowsCount = 0;
// walk through the newspaper rows
for (int nr = 0; nr < newspaperRows; nr++) {
boolean rowStartRendered = false;
// walk through the newspaper columns
for (int nc = 0; nc < newspaperColumns; nc++) {
// the current row in the 'real' table
int currentRow;
if (newspaperHorizontalOrientation) {
currentRow = nr * newspaperColumns + nc + first;
} else {
currentRow = nc * newspaperRows + nr + first;
}
// if this row is not to be rendered
if (currentRow >= last) {
continue;
}
// bail if any row does not exist
uiData.setRowIndex(currentRow);
if (!uiData.isRowAvailable()) {
log.severe("Row is not available. Rowindex = " + currentRow);
break;
}
if (nc == 0) {
// first column in table, start new row
beforeRow(facesContext, uiData);
// is the current row listed in the bodyrows attribute
if (ArrayUtils.contains(bodyrows, currentRow)) {
// close any preopened TBODY element first
if (bodyrowsCount != 0) {
HtmlRendererUtils.writePrettyLineSeparator(facesContext);
writer.endElement(HTML.TBODY_ELEM);
}
HtmlRendererUtils.writePrettyLineSeparator(facesContext);
writer.startElement(HTML.TBODY_ELEM, uiData);
// Do not attach bodyrowsCount to the first TBODY
// element, because of backward compatibility
writer.writeAttribute(HTML.ID_ATTR, component.getClientId(facesContext) + ":tbody_element" + (bodyrowsCount == 0 ? "" : bodyrowsCount),
null);
bodyrowsCount++;
}
HtmlRendererUtils.writePrettyLineSeparator(facesContext);
renderRowStart(facesContext, writer, uiData, styles, nr);
rowStartRendered = true;
}
List<UIComponent> children = null;
for (int j = 0, size = getChildCount(component); j < size; j++) {
if (children == null) {
children = getChildren(component);
}
UIComponent child = children.get(j);
if (child.isRendered()) {
boolean columnRendering = child instanceof UIColumn;
if (columnRendering) {
beforeColumn(facesContext, uiData, j);
}
encodeColumnChild(facesContext, writer, uiData, child, styles, nc * uiData.getChildCount() + j);
if (columnRendering) {
afterColumn(facesContext, uiData, j);
}
}
}
if (hasNewspaperTableSpacer(uiData)) {
// draw the spacer facet
if (nc < newspaperColumns - 1) {
renderSpacerCell(facesContext, writer, uiData);
}
}
}
if (rowStartRendered) {
renderRowEnd(facesContext, writer, uiData);
afterRow(facesContext, uiData);
}
}
if (bodyrowsCount != 0) {
// close the last TBODY element
HtmlRendererUtils.writePrettyLineSeparator(facesContext);
writer.endElement(HTML.TBODY_ELEM);
}
}
#Override
protected void renderRowStart(FacesContext facesContext, ResponseWriter writer, UIData uiData, Styles styles, int rowStyleIndex) throws IOException {
writer.startElement(HTML.TR_ELEM, null); // uiData);
renderRowStyle(facesContext, writer, uiData, styles, rowStyleIndex);
Object obj = uiData.getRowData();
boolean isHide = false;
if (obj instanceof TableRow) {
isHide = ((TableRow) obj).isHide();
}
if (isHide) {
writer.writeAttribute("style", "display: none;", null);
}
Object rowId = uiData.getAttributes().get(org.apache.myfaces.shared.renderkit.JSFAttr.ROW_ID);
if (rowId != null) {
writer.writeAttribute(HTML.ID_ATTR, rowId.toString(), null);
}
}
private void encodeInnerHtmlUnknownRowCount(FacesContext facesContext, UIComponent component) throws IOException {
UIData uiData = (UIData) component;
ResponseWriter writer = facesContext.getResponseWriter();
Styles styles = getStyles(uiData);
Integer[] bodyrows = getBodyRows(facesContext, component);
int bodyrowsCount = 0;
int first = uiData.getFirst();
int rows = uiData.getRows();
int currentRow = first;
boolean isRowRendered = false;
while (true) {
uiData.setRowIndex(currentRow);
if (!uiData.isRowAvailable()) {
break;
}
isRowRendered = true;
// first column in table, start new row
beforeRow(facesContext, uiData);
// is the current row listed in the bodyrows attribute
if (ArrayUtils.contains(bodyrows, currentRow)) {
// close any preopened TBODY element first
if (bodyrowsCount != 0) {
HtmlRendererUtils.writePrettyLineSeparator(facesContext);
writer.endElement(HTML.TBODY_ELEM);
}
HtmlRendererUtils.writePrettyLineSeparator(facesContext);
writer.startElement(HTML.TBODY_ELEM, uiData);
// Do not attach bodyrowsCount to the first TBODY element,
// because of backward compatibility
writer.writeAttribute(HTML.ID_ATTR, component.getClientId(facesContext) + ":tbody_element" + (bodyrowsCount == 0 ? "" : bodyrowsCount), null);
bodyrowsCount++;
}
HtmlRendererUtils.writePrettyLineSeparator(facesContext);
renderRowStart(facesContext, writer, uiData, styles, currentRow);
List<UIComponent> children = null;
for (int j = 0, size = getChildCount(component); j < size; j++) {
if (children == null) {
children = getChildren(component);
}
UIComponent child = children.get(j);
if (child.isRendered()) {
boolean columnRendering = child instanceof UIColumn;
if (columnRendering) {
beforeColumn(facesContext, uiData, j);
}
encodeColumnChild(facesContext, writer, uiData, child, styles, j);
if (columnRendering) {
afterColumn(facesContext, uiData, j);
}
}
}
renderRowEnd(facesContext, writer, uiData);
afterRow(facesContext, uiData);
currentRow++;
if (rows > 0 && currentRow - first > rows) {
break;
}
}
if (!isRowRendered) {
// nothing to render, to get valid xhtml we render an empty dummy
// row
writer.startElement(HTML.TBODY_ELEM, uiData);
writer.writeAttribute(HTML.ID_ATTR, component.getClientId(facesContext) + ":tbody_element", null);
writer.startElement(HTML.TR_ELEM, uiData);
writer.startElement(HTML.TD_ELEM, uiData);
writer.endElement(HTML.TD_ELEM);
writer.endElement(HTML.TR_ELEM);
writer.endElement(HTML.TBODY_ELEM);
return;
}
if (bodyrowsCount != 0) {
// close the last TBODY element
HtmlRendererUtils.writePrettyLineSeparator(facesContext);
writer.endElement(HTML.TBODY_ELEM);
}
}
private Integer[] getBodyRows(FacesContext facesContext, UIComponent component) {
Integer[] bodyrows = null;
String bodyrowsAttr = (String) component.getAttributes().get(JSFAttr.BODYROWS_ATTR);
if (bodyrowsAttr != null && !"".equals(bodyrowsAttr)) {
String[] bodyrowsString = StringUtils.trim(StringUtils.splitShortString(bodyrowsAttr, ','));
// parsing with no exception handling, because of JSF-spec:
// "If present, this must be a comma separated list of integers."
bodyrows = new Integer[bodyrowsString.length];
for (int i = 0; i < bodyrowsString.length; i++) {
bodyrows[i] = new Integer(bodyrowsString[i]);
}
} else {
bodyrows = ZERO_INT_ARRAY;
}
return bodyrows;
}
}
Use the empty css selector as suggested here, but with tr instead of td. This worked for me.
https://stackoverflow.com/a/19177424
As described here: https://developer.mozilla.org/en-US/docs/Web/CSS/:empty
This selector works on all current browsers.
<style>
tr:empty {
display: none;
}
</style>
I've successfully hidden rows by putting a rendered attribute in all the <h:column> tags. The problem is that it suppresses the table headers. If your table has no table headers (they are <f:facet name="header"> tags embedded in the <h:column>), this approach might work for you.
I ended up using multiple lists in the backing bean, as I needed the table headers.