Here i m passing only single param from telerik to javascript function. i need to pass another param also
<a href="javascript:void(0);" onclick="AddOdometer(<%: b.VehicleRepositoryId %>)"
title="ADDTrip" id="A1">Add Distance</a>
whole code for reference
<% Html.Telerik().Grid(Model.VehicleList)
.Name("VehiclesRepositoryGrid")
.Columns(colums =>
{
colums.Bound(b => b.TruckNumber).Title("Vehicle Number")
.FooterTemplate(() =>
{%>
Total:
<%})
.Width(100);
colums.Bound(b => b.Month);
colums.Bound(b => b.FuelType).Title("Fuel Type");
colums.Bound(b => b.TotalDistance).Title("Distance")
.FooterTemplate(() =>
{%>
<%= Model.VehicleList.Sum(v=>v.TotalDistance)%>
<%})
.Width(100);
colums.Bound(b => b.TotalFuel).Title("Fuel")
.FooterTemplate(() =>
{%>
<%= Model.VehicleList.Sum(v => v.TotalFuel)%>
<%})
.Width(100);
colums.Bound(b => b.Mileage);
colums.Template(b =>
{
%>
<% if (b.TotalDistance == 0)
{%>
<a href="javascript:void(0);" onclick="AddOdometer(<%: b.VehicleRepositoryId %>)"
title="ADDTrip" id="A1">Add Distance</a>
<%}
else
{ %>
<a href="javascript:void(0);" onclick="EditOdometer(<%: b.VehicleRepositoryId %>)"
title="Edit">
<img src="<%= ResolveUrl("~/Content/Images/Edit.gif")%>" alt="Edit" title="Edit"
class="vaM" /></a> | <a href="javascript:void(0);" onclick="DeleteOdometer(<%: b.VehicleRepositoryId %>)"
id="DeleteVehicle">
<img src="<%= ResolveUrl("~/Content/Images/Delete.gif")%>" alt="Delete" title="Delete"
class="vaM" /></a>
<% } %>
<%
}).Title("Actions")
.Width(100).HtmlAttributes(new { #class = "taC" });
})
.Groupable(settings => settings.Groups(groups =>
{
groups.Add(o => o.TruckNumber);
if (ViewData["Grouping"] != null)
{
groups.Add(o => o.Month);
}
}))
.Scrollable(scrolling => scrolling.Enabled(false))
.Sortable(sorting => sorting.Enabled(true))
.Pageable(paging => paging.Enabled(true))
.Filterable(filtering => filtering.Enabled(true))
.Footer(true)
.Render();
%>
Not sure what your question is, is this what you want to achieve?
<a href="javascript:void(0);"
onclick="AddOdometer(<%: b.VehicleRepositoryId %>, <%: b.SecondParam %>)"
title="ADDTrip" id="A1">Add Distance</a>
Related
I am buidling a mvc web application with entity framework.
Error:
An exception of type 'System.ObjectDisposedException' occurred in
EntityFramework.dll but was not handled in user code
Additional information: The ObjectContext instance has been disposed
and can no longer be used for operations that require a connection.
This is the entity framework part:
Like you see I already include "Alineas" and do .ToList()
public IList<Kop> Handle(RetrieveKoppenForDocumentQuery query)
{
using (var db = new BmDataContext())
{
var koppen = db.Kop.Where(s => s.Document.Id == query.Id)
.Include(s => s.TegelAfbeelding)
.Include(s => s.CollageAfbeeldingen)
.Include(s => s.FinancieleAfbeeldingen)
.Include(s => s.Alineas)
.ToList();
return _orderKoppenByIndex(koppen);
}
}
This is the view KopListItems.cshtml:
#using PGE.Bestuursmonitor.Contracts.DataTypes
#model IList<Kop>
#* Helper for recursively rendering koppen*#
#helper SortableItem(Kop kop)
{
<div class="sortable-item" data-kopid="#kop.Id">
<div class="row">
<div class="col-md-7 title-column">
<i class="fa fa-arrows"></i> #kop.Titel
</div>
<div class="col-md-5">
<div class="col-md-3">
<span>
#kop.KopType
</span>
</div>
<div class="col-md-3">
<span>
#kop.Status
</span>
</div>
<div class="col-md-6">
<span class="pull-right">
#if (#kop.Alineas != null) // on this line I receive the exception
{
// here I would like to do some logic
}
</span>
</div>
</div>
</div>
<div class="sortable-container">
#foreach (var subKop in kop.Koppen)
{
#SortableItem(subKop);
}
</div>
</div>
}
#* Recursively render all kop items *#
<div id="koppen_sortable" class="sortable-container">
#foreach (Kop kop in Model)
{
#SortableItem(kop);
}
</div>
This is the view KoppenList.cshtml:
#model PGE.Bestuursmonitor.ViewModels.Koppen.IKoppenListViewModel
<h1>#Model.DocumentTitel</h1>
#* Render kop list header *#
<div id="koppen_sortable_header">
<div class="row">
<div class="col-md-7"><strong>Titel</strong></div>
<div class="col-md-5">
<div class="col-md-3">
<strong>Type</strong>
</div>
<div class="col-md-3">
<strong>Status</strong>
</div>
<div class="col-md-6">
<span class="pull-right">
<button type="button" id="btn_add_sub" class="btn btn-success" title="Kop aanmaken" role="button" onclick="BM.Koppen.LoadAddKopView(null);">
<i class="fa fa-plus fa-lg"></i> Kop aanmaken
</button>
</span>
</div>
</div>
</div>
</div>
<div id="koppen_sortable_body">
#{ Html.RenderPartial("~/Views/Koppen/KopListItems.cshtml", #Model.Koppen); }
</div>
#* Store document id in html DOM, so javascript can reach it from multiple places *#
<input type="hidden" id="document_id" value="#Model.DocumentId" />
Action in controller:
[HttpGet]
public ActionResult KoppenList(string id)
{
ViewBag.PageId = id;
Document document = _retrieveStartPcDocumentQueryHandler.Handle(new RetrieveStartPcDocumentQuery());
RetrieveKoppenForDocumentQuery query = new RetrieveKoppenForDocumentQuery
{
Id = document.Id
};
IList<Kop> koppen = _retrieveKoppenForDocumentQueryHandler.Handle(query);
_koppenListViewModel.Koppen = koppen;
_koppenListViewModel.DocumentTitel = document.Titel;
_koppenListViewModel.DocumentId = document.Id;
return View("~/Views/Koppen/KoppenList.cshtml", _koppenListViewModel);
}
Like you see in KopListItems.cshtml there are 2 foreach loops. The outer foreach loop is working fine and can read "Alineas". The inner foreach which shows the sub items gives this strange error. What is going wrong? Im stuck.
This is the solution. You need to get the alineas and content also on sub level:
public IList<Kop> Handle(RetrieveKoppenForDocumentQuery query)
{
using (var db = new BmDataContext())
{
var koppen = db.Kop.Where(s => s.Document.Id == query.Id)
.Include(s => s.TegelAfbeelding)
.Include(s => s.CollageAfbeeldingen)
.Include(s => s.FinancieleAfbeeldingen)
.Include(s => s.Alineas.Select(a => a.Content))
.Include(s => s.Koppen.Select(k => k.Alineas.Select(a => a.Content)))
.Include(s => s.Koppen.Select(k => k.Koppen.Select(x => x.Alineas.Select(a => a.Content))))
.ToList();
return _orderKoppenByIndex(koppen);
}
}
I am having a slight issue with a rails app I am working on. I am utilizing Carrierwave, Nested_form, Simple_form, and Jquery-file-upload gems.
The majority of everything is working fine, with the exception of the data.
I have two models, a Project Model and an Attachments Model.
When the Project form is submitted, all the files upload as they should, a record in the attachments model is created as it should (one per file). But as for the projects model, a record is created for each file as well.
I can't seem to figure out (on a single form, with single submit) how to get only one record for the project and multiple records for the attachments.
Any help would be appreciated, I've outlined my code below. I'd like to avoid a two step process if possible, but if someone could point me in the right direction that would help.
Project Model
class Project < ActiveRecord::Base
has_many :attachments, :dependent => :destroy
accepts_nested_attributes_for :attachments, :allow_destroy => true
def generate_token
self.token = loop do
random_token = SecureRandom.urlsafe_base64
break random_token unless Project.where(token: random_token).exists?
end
end
end
Attachment Model
class Attachment < ActiveRecord::Base
belongs_to :project, :polymorphic => true
include Rails.application.routes.url_helpers
mount_uploader :file, AttachmentUploader
def to_jq_upload
{
"name" => read_attribute(file),
"url" => file.url,
"size" => file.size,
"delete_url" => attachment_path(:id => id),
"delete_type" => "DELETE"
}
end
end
Projects Controller
class ProjectsController < ApplicationController
def index
#projects = Project.all
respond_to do |format|
format.html
format.json { render json: #projects }
end
end
def new
#project = Project.new
#project.token = #project.generate_token
#attachments = #project.attachments.build
end
def create
#project = Project.new(project_params)
respond_to do |format|
if #project.save
format.html { redirect_to projects_url, notice: 'Project was successfully created.' }
format.json { render json: #project, status: :created, location: #project }
else
format.html {}
format.json {}
end
end
end
def destroy
#project = Project.find(params[:id])
#project.destroy
respond_to do |format|
format.html { redirect_to projects_url }
format.json { head :no_content }
end
end
private
def project_params
params.require(:project).permit(:name, :token, :number_of_pages, :number_of_copies, :flat_page_size, :trim_page_size, :purchase_order_number, :preferred_delivery_date, :delivery_method, :delivery_instructions, :project_instructions, attachments_attributes: [:id, :attachment, :name, :filename, :file, :project_token, :branch])
end
end
Attachments Controller
class AttachmentsController < ApplicationController
before_filter :the_project
def index
#attachments = Attachment.where("project_id = ?", the_project)
render :json => #attachments.collect { |p| p.to_jq_upload }.to_json
end
def create
#project = Project.find(params[:project_id])
#attachment = Attachment.new(attachment_params)
if #attachment.save
respond_to do |format|
format.html { render :json => [#attachment.to_jq_upload].to_json, :content_type => 'text/html', :layout => false }
format.json { render :json => {files: [#attachment.to_jq_upload]}.to_json }
end
else
render :json => [{ :error => "custom_failure "}], :status => 304
end
end
def destroy
#attachment = Attachment.find(params[:id])
#attachment.destroy
render :json => true
end
private
def the_project
#project = Project.find(params["project_id"])
end
end
New Project Form (app/views/projects/new.html.erb)
<h2>New Project</h2>
<br />
<%= simple_nested_form_for #project, :defaults => { :wrapper_html => {:class => 'form-group'}, :input_html => { :class => 'form-control' } }, :html => { :multipart => true, :id => "fileupload", :class => 'horizontal-form', :role => "form" } do |f| %>
<div class="row">
<div class="col-lg-12">
<%= f.input :name, :label => "Project Name / Description", :class => 'col-lg-12' %>
<%= f.hidden_field :token %>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<%= f.input :number_of_pages %>
<%= f.input :flat_page_size %>
<%= f.input :purchase_order_number %>
</div>
<div class="col-lg-6">
<%= f.input :number_of_copies %>
<%= f.input :trim_page_size, :label => 'Finished Size <em><small>(If Different from Flat Page Size)</small></em>' %>
<%= f.input :preferred_delivery_date, :as => :text %>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<%= f.input :delivery_method %>
</div>
<div class="col-lg-6">
<%= f.input :project_instructions %>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<select id="branches">
<option>Calgary Downtown</option>
<option>Calgary South</option>
<option>Edmonton</option>
<option>Kelowna</option>
</select>
</div>
</div>
<br />
<div class="row fileupload-buttonbar">
<div class="col-lg-7">
<%= fields_for :attachments do |a| %>
<span class="btn btn-success fileinput-button">
<i class="glyphicon glyphicon-plus"></i>
<span>Add files...</span>
<%= a.file_field :file, :name => 'project[attachments_attributes][0][file]', :multiple => true %>
</span>
<button type="submit" class="btn btn-primary start">
<i class="glyphicon glyphicon-upload"></i>
<span>Start Upload</span>
</button>
<button type="reset" class="btn btn-warning cancel">
<i class="glyphicon glyphicon-ban-circle"></i>
<span>Cancel Upload</span>
</button>
<button type="button" class="btn btn-danger delete">
<i class="glyphicon glyphicon-trash"></i>
<span>Delete Upload</span>
</button>
<%= a.hidden_field :branch, :value => "Calgary Downtown" %>
<%= a.hidden_field :project_token, :value => #project.token %>
<% end %>
</div>
<div class="col-lg-5">
<div class="progress progress-success progress-striped active fade">
<div class="bar" style="width:0%"></div>
</div>
</div>
</div>
<div class="row fileupload-loading"></div>
<div class="row">
<table class="table table-striped">
<tbody class="files" data-toggle="modal-gallery" data-target="#modal-gallery">
</tbody>
</table>
</div>
<% end %>
<script>
var fileUploadErrors = {
maxFileSize: 'File is too big',
minFileSize: 'File is too small',
acceptFileTypes: 'Filetype not allowed',
maxNumberOfFiles: 'Max number of files exceeded',
uploadedBytes: 'Uploaded bytes exceed file size',
emptyResult: 'Empty file upload result'
};
</script>
<!-- The template to display files available for upload -->
<script id="template-upload" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
<tr class="template-upload fade">
<td class="preview"><span class="fade"></span></td>
<td class="name"><span>{%=file.name%}</span></td>
<td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>
{% if (file.error) { %}
<td class="error" colspan="2"><span class="label label-important">{%=locale.fileupload.error%}</span> {%=locale.fileupload.errors[file.error] || file.error%}</td>
{% } else if (o.files.valid && !i) { %}
<td>
<div class="progress progress-success progress-striped active"><div class="bar" style="width:0%;"></div></div>
</td>
<td class="start">{% if (!o.options.autoUpload) { %}
<button class="btn btn-primary">
<i class="icon-upload icon-white"></i>
<span>{%=locale.fileupload.start%}</span>
</button>
{% } %}</td>
{% } else { %}
<td colspan="2"></td>
{% } %}
<td class="cancel">{% if (!i) { %}
<button class="btn btn-warning">
<i class="icon-ban-circle icon-white"></i>
<span>{%=locale.fileupload.cancel%}</span>
</button>
{% } %}</td>
</tr>
{% } %}
</script>
<!-- The template to display files available for download -->
<script id="template-download" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
<tr class="template-download fade">
{% if (file.error) { %}
<td></td>
<td class="name"><span>{%=file.name%}</span></td>
<td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>
<td class="error" colspan="2"><span class="label label-important">{%=locale.fileupload.error%}</span> {%=locale.fileupload.errors[file.error] || file.error%}</td>
{% } else { %}
<td class="preview">{% if (file.thumbnail_url) { %}
<img src="{%=file.thumbnail_url%}">
{% } %}</td>
<td class="name">
{%=file.name%}
</td>
<td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>
<td colspan="2"></td>
{% } %}
<td class="delete">
<button class="btn btn-danger" data-type="{%=file.delete_type%}" data-url="{%=file.delete_url%}">
<i class="icon-trash icon-white"></i>
<span>{%=locale.fileupload.destroy%}</span>
</button>
<input type="checkbox" name="delete" value="1">
</td>
</tr>
{% } %}
</script>
<script type="text/javascript" charset="utf-8">
$(function () {
var num_added = 0;
var added = 0;
var all_data = {};
$('#branches').change(function() {
var test = $("option:selected",this).text();
$('#project_attachments_attributes_0_branch').val(test);
});
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload({
sequentialUploads: true,
});
});
</script>
I'm working on more or less that exact same issue (mine involves stock_items - not projects, but anyways...)
One issue is the #fileupload.fileupload which initializes the entire form - and that will post your project, which you will not want to
I've not solved that one yet - but somehow 'we' have to make the parent form not POST
I believe you need to include the index of the 'parent' instance in the input, in this case, Project. So:
<%= a.file_field :file, :name => 'project[*index*][attachments_attributes][0][file]', :multiple => true %>
I want to be able to upload an image using a view.
So far here's what I've done based on this blog here:
I have a model extension that contains the following item:
[FileSize(10240)]
[FileTypes("jpg,jpeg,png")]
public HttpPostedFileBase mCardImage { get; set; }
FYI: the FileSize and FileTypes attributes are shaped like this:
public class FileSizeAttribute : ValidationAttribute
{
private readonly int mMaxSize;
public FileSizeAttribute(int _maxSize)
{
mMaxSize = _maxSize;
}
public override bool IsValid(object _value)
{
if (_value == null)
{
return true;
}
return mMaxSize > (_value as HttpPostedFile).ContentLength;
}
public override string FormatErrorMessage(string _name)
{
return string.Format("The file size shoud not exceed {0}", mMaxSize);
}
}
public class FileTypesAttribute: ValidationAttribute
{
private readonly List<string> mTypes;
public FileTypesAttribute(string _types)
{
mTypes = _types.Split(',').ToList();
}
public override bool IsValid(object _value)
{
if (_value == null)
{
return true;
}
var fileExt = System.IO.Path.GetExtension((_value as HttpPostedFile).FileName).Substring(1);
return mTypes.Contains(fileExt, StringComparer.OrdinalIgnoreCase);
}
public override string FormatErrorMessage(string _name)
{
return String.Format("Invalid file type. Only the following types: {0} are supported.",
String.Join(", ", mTypes));
}
}
And my view is rendered like this:
#model MyApp.Utilities.ModelExtensions.CardInfoExtension
<h2>Create new Card</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<div class="formStyle">
<div class="float-right baseMargin">
#Html.Image(Model.mCardImageLink, Model.mCardName, null)<br/>
#Html.TextBoxFor(_item => _item.mCardImage, new { #type = "file" } )
#Html.ValidationMessageFor(_item => _item.mCardImage)
</div>
#Html.HiddenFor(_item => _item.mCardImageLink)
<div class="baseFontSize">
#Html.LabelFor(_item => _item.mCardName)
</div>
<div class="baseFontSize">
#Html.EditorFor(_item => _item.mCardName)
#Html.ValidationMessageFor(_item => _item.mCardName)
</div>
<div class="baseFontSize">
#Html.LabelFor(_item => _item.mCardNumber)
</div>
<div class="baseFontSize">
#Html.EditorFor(_item => _item.mCardNumber)
#Html.ValidationMessageFor(_item => _item.mCardNumber)
</div>
<div class="baseFontSize">
#Html.LabelFor(_item => _item.mCardColor)
</div>
<div>
#Html.Image("~\\Images\\Functional\\blueColor.jpeg", "Blue", null) #Html.CheckBoxFor(_item => _item.mBlueColor, Model.mBlueColor)
#Html.Image("~\\Images\\Functional\\redColor.jpeg", "Blue", null) #Html.CheckBoxFor(_item => _item.mRedColor, Model.mRedColor)
#Html.Image("~\\Images\\Functional\\greenColor.jpeg", "Blue", null) #Html.CheckBoxFor(_item => _item.mGreenColor, Model.mGreenColor) <br/>
#Html.Image("~\\Images\\Functional\\blackColor.jpeg", "Blue", null) #Html.CheckBoxFor(_item => _item.mBlackColor, Model.mBlackColor)
#Html.Image("~\\Images\\Functional\\whiteColor.jpeg", "Blue", null) #Html.CheckBoxFor(_item => _item.mWhiteColor, Model.mWhiteColor)<br/>
</div>
<div class="baseFontSize">
#Html.LabelFor(_item => _item.mCardManaCost)
</div>
<div class="baseFontSize">
#Html.EditorFor(_item => _item.mCardManaCost)
#Html.ValidationMessageFor(_item => _item.mCardManaCost)
</div>
<div class="baseFontSize">
#Html.LabelFor(_item => _item.mCardManaConverted)
</div>
<div class="baseFontSize">
#Html.EditorFor(_item => _item.mCardManaConverted)
#Html.ValidationMessageFor(_item => _item.mCardManaConverted)
</div>
<div class="baseFontSize">
#Html.LabelFor(_item => _item.mCardType)
</div>
<div class="baseFontSize">
#Html.DropDownListFor(_item => _item.mCardType, Model.mCardTypeList, String.Empty)
#Html.ValidationMessageFor(_item => _item.mCardType)<br/>
<span class="baseFontSize">Additional Type</span>
#Html.TextBoxFor(_item => _item.mAdditionalCardType)
</div>
<div class="baseFontSize">
#Html.LabelFor(_item => _item.mCardPower)
</div>
<div class="baseFontSize">
#Html.DropDownListFor(_item => _item.mCardPower, Model.mCardPowerList, "--- Select a value---")
#Html.ValidationMessageFor(_item => _item.mCardPower)
</div>
<div class="baseFontSize">
#Html.LabelFor(_item => _item.mCardToughness)
</div>
<div class="baseFontSize">
#Html.DropDownListFor(_item => _item.mCardToughness, Model.mCardToughnessList, "--- Select a value---")
#Html.ValidationMessageFor(_item => _item.mCardToughness)
</div>
<div class="baseFontSize">
#Html.LabelFor(_item => _item.mCardRarity)
</div>
<div class="baseFontSize">
#Html.DropDownListFor(_item => _item.mCardRarity, Model.mCardRarityList, String.Empty)
#Html.ValidationMessageFor(_item => _item.mCardRarity)
</div>
<div class="baseFontSize">
#Html.LabelFor(_item => _item.mCardTextAbilities)
</div>
<div class="baseFontSize">
#Html.TextAreaFor(_item => _item.mCardTextAbilities, new { #class = "textAreaWide" } )
#Html.ValidationMessageFor(_item => _item.mCardTextAbilities)
</div>
<div class="baseFontSize">
#Html.LabelFor(_item => _item.mCardTextFlavor)
</div>
<div class="baseFontSize">
#Html.TextAreaFor(_item => _item.mCardTextFlavor, new { #class = "textAreaWide" } )
#Html.ValidationMessageFor(_item => _item.mCardTextFlavor)
</div>
<div class="baseFontSize">
#Html.LabelFor(_item => _item.mCardArtistName)
</div>
<div class="baseFontSize">
#Html.EditorFor(_item => _item.mCardArtistName)
#Html.ValidationMessageFor(_item => _item.mCardArtistName)
</div>
<div class="baseFontSize">
#Html.LabelFor(_item => _item.mCardSet)
</div>
<div class="baseFontSize">
#Html.DropDownListFor(_item => _item.mCardSetID, ViewBag.List as SelectList, "--- Select Card Set ---", new { #class = "CardSetInfo"} )
#Html.ValidationMessageFor(_item => _item.mCardSet)
</div>
<div id="buttonField">
<input type="submit" value="Create" onclick="needToConfirm = false"/>
</div>
</div>
}
Finally, my controller action receives the model in which the file is located:
[HttpPost]
public ActionResult CreateCard(CardInfoExtension _card)
{
// Do some code here...
}
My question is: why does the mCardImage is ALWAYS null? I've tried uploading the whole thing manually with an input:
<input type="file" name="_file">
But, once again, in my controller method, the value is null. Why? Can anybody help me out?
I was missing this line in my view:
#using (Html.BeginForm("CreateCard", "Card", FormMethod.Post, new { enctype = "multipart/form-data" }))
Seems like by default Html views are not able to upload without this line. Adding this instead of the classic Html.BeginForm() solved the case!
You need to set the name of the <input> to match the name of the model property you want it to bind to.
I want to create tasks by using ajax with loader.
Here is my View -
<%= form_for(#task, :remote => "true") do |f| %>
<center><h3>Organize Your Tasks</h3></center>
<table class="table table-bordered table-condensed table-striped">
<tr>
<td>
<%= f.select :taskcategory, options_for_select(["Money/Career", "Relationship", "Safety", "Health Care", "God", "Hobbies", "Society"]), {}, {:multiple => false} %>
</td>
<td style="width:120px;">
<%= f.text_field :taskname, :placeholder => "Task Name" %>
</td>
<td>
<%= f.select :importance, options_for_select(["Highly Important", "Important", "Less Important"]), {}, {:multiple => false} %></center>
</td>
<td style="width:120px;">
<%= f.text_field :startdate , :id => "from", :placeholder => "Start Date", :value => "#{Date.today.strftime("%d/%m/%Y") }" %>
</td>
<td style="width:120px;">
<%= f.text_field :targetdate , :id => "to", :placeholder => "End Date", :disabled => "ture"%>
</td>
<td>
<%= f.submit "Create", class: "btn"%>
</td>
</tr>
</table>
<% end %>
And here is my controller -
def create
#task= current_user.tasks.build(params[:task])
respond_to do |format|
if #task.save
flash[:success] = "Task created!"
format.html {redirect_to root_url }
format.js { redirect_to}
else
format.html { render 'static_pages/index'}
end
end
end
Here I write a code to show all tasks
<div class="tabbable" style="margin-left:-50px" >
<ul class="nav nav-tabs span10" id="myTab" style="margin-left:50px">
<li class="active">All Tasks(<%= current_user.tasks.where(:status => 'active').count %>)</li>
<li >Dreams(<%= current_user.tasks.where(:importance => 'Highly Important', :status => 'active').count %>)</li>
<li ><a href="#tab3" >Today's Tasks(<%= current_user.tasks.where(:targetdate => Date.today.to_s, :status => 'active').count %>)</a></li>
<li ><a href="#tab4" >Imp Tasks(<%= current_user.tasks.where(:importance => 'Important', :status => 'active').count %>)</a></li>
<li id="fat-menu" class="dropdown aa">
Others
<ul class="dropdown-menu">
<li><a href="#tab5" >Postpone(<%= current_user.tasks.where(:status => 'postpone').count %>)</a></li>
<li><a href="#tab6" >Satisfied(<%= current_user.tasks.where(:status => 'satisfied').count%>)</a></li>
<li><a href="#tab7" >Unsatisfied(<%= current_user.tasks.where(:status => 'unsatisfied').count%>)</a></li>
<li><a href="#tab8" >Closed(<%= current_user.tasks.where(:status => 'closed').count%>)</a></li>
</ul>
</li>
</ul>
<div class="tab-content span10" >
<div class="tab-pane active" id="tab1">
<%= render 'shared/feed' %>
</div>
<div class="tab-pane" id="tab2">
<%= render 'shared/feed_dream' %>
</div>
<div class="tab-pane" id="tab3">
<%= render 'shared/feed_urgent' %>
</div>
<div class="tab-pane" id="tab4">
<%= render 'shared/feed_important' %>
</div>
<div class="tab-pane" id="tab5">
<%= render 'shared/feed_postpone' %>
</div>
<div class="tab-pane" id="tab6">
<%= render 'shared/feed_satisfied' %>
</div>
<div class="tab-pane" id="tab7">
<%= render 'shared/feed_unsatisfied' %>
</div>
<div class="tab-pane" id="tab8">
<%= render 'shared/feed_closed' %>
</div>
</div>
Here is my create.js.ejb ---
page.replace_html('index' , redirect_to root_url)
When i submit my task then it creates in database but page is not updated. When i again refresh the page then task is showing. I know the problem in create.js.ejb file. How can i show update tasks in my table??
First of all make sure that you have included jquery and jquery_ujs into your application.js file.
Its a bad habit to redirect from the view. Make it format.js { redirect_to root_url}
And use *.js.erb template instead of rjs template.
In create.js.erb you might do something like this
$("#some_div").append("some HTML content that is related to created record")
Hope this helps
page.replace_html('index' , redirect_to root_url) // this is invalid
"page.replace_html" no longer works in rails 3
In create.js.erb
alert("record created");
// or update div with id some_div_id
$("#some_div_id").html("<%= escape_javascript(render :partial => 'some_partial') %>");
I want to add an image to a data grid column, I am using telerik grid for this, however I get the following error, its on Line 51:
Compiler Error Message: CS1525: Invalid expression term ')'
Source Error:
Line 49: column.Bound(o => o.HoursWorked).Title("Hours");
Line 50: column.Template(o =>
Line 51: {%>
Line 52: <img src="/Content/img/delete.png" alt="Delete" title="Delete"/>
Line 53: <%
Here is how I am trying to add an image to the column:
<div>
<%=Html.CustomGridFor("Hours", "WorkHours", "HoursWorked", GridOptions.EnableSelecting, Model).Columns(column =>
{
column.Bound(o => o.DateWorked).Title("Date").Width("65px");
column.Bound(o => o.Description).Title("Description").Width("120px");
column.Bound(o => o.HoursWorked).Title("Hours");
column.Template(o =>
{%>
<img src="/Content/img/delete.png" alt="Delete" title="Delete" onclick="javascript:deleteHours();" />
<%
}).Title("").ClientTemplate(
"<img src=\"/Content/img/delete.png\" alt=\"Delete\" title=\"Delete\"/>"
).Width(15);
}).HtmlAttributes(new { style = "width: 270px;" });
%>
</div>
Tried this too:
<div>
<%=Html.CustomGridFor("Hours", "WorkHours", "HoursWorked", GridOptions.EnableSelecting, Model).Columns(column =>
{
column.Bound(o => o.DateWorked).Title("Date").Width("65px");
column.Bound(o => o.Description).Title("Description").Width("120px");
column.Bound(o => o.HoursWorked).Title("Hours");
column.Template(o =>
{
%>
<img
alt="Delete"
src="/Content/img/delete.png"
/>
<%
});
</div>
Try to use this:
<div>
<%=Html.CustomGridFor("Hours", "WorkHours", "HoursWorked", GridOptions.EnableSelecting, Model).Columns(column =>
{
column.Bound(o => o.DateWorked).Title("Date").Width("65px");
column.Bound(o => o.Description).Title("Description").Width("120px");
column.Bound(o => o.HoursWorked).Title("Hours");
column.Template(o => string.Empty).Title("")
.ClientTemplate(
"<img src=\"/Content/img/delete.png\" alt=\"Delete\" title=\"Delete\"/>")
.Width(15);
}).HtmlAttributes(new { style = "width: 270px;" });
%>
</div>