command link reRender in salesforce - javascript

I am developing a visualforce page for force.com site. I am using apex command link for do some action. the code is given below:
<ul>
<li class="pill-none"><span>
<apex:commandLink action="{!processOnSelected}" reRender="windowOpenPanel">Print
<apex:param name="commandAtt" value="print"/>
</apex:commandLink>
</span>
<apex:outputPanel id="windowOpenPanel">
<apex:outputPanel rendered="{!isOpen}">
<script type="text/javascript">
window.open('http://invoicedetails.dev.cs16.force.com/EnterCode/InvoicePDF?invoiceId={!idString}');
</script>
</apex:outputPanel>
</apex:outputPanel>
</li></ul>
but is not going to class method processOnSelected(). It is giving js error
actionUrl.indexOf is not a function
below is my controller method code:
public void processOnSelected () {
String command = Apexpages.currentPage().getParameters().get('commandAtt');
idString = '';
isOpen=true;
Set<Id> selectedIdSet = new Set<Id>();
if (command=='print' || command=='payment') {
//wfdList = new List<WrapForDescription>();
//System.debug('__wfdList__'+wfdList);
for(WrapForDescription tmpList : wfdList) {
if(tmpList.checked) {
//WrapForDescription selected = new WrapForDescription();
//selected.wrapOpp = tmpList.wrapOpp;
//wfdList.add(selected);
selectedIdSet.add(tmpList.wrapOpp.Id);
idString+= tmpList.wrapOpp.Id+',';
//System.debug('__True__');
}
}
idString = idString.substring(0, idString.length()-1);
}
else if (command=='onePDF') {
idString = id;
}
Blob idBlob = Blob.valueOf(idString);
idString = Encodingutil.base64Encode(idBlob);
System.debug('__idString__'+idString);
System.debug('__selectedIdSet__'+selectedIdSet);
if (command=='payment') {
page = 'beforePaymentAll';
AggregateResult oppSumAmount = [select SUM(Amount) total from Opportunity where Id IN :selectedIdSet];
//accObj = [select Name, convertCurrency(Unpaid_Opportunity_Amount__c), convertCurrency(Paid_Opportunity_Amount__c) from Account where Id =:accId];
unpaid_amount = (Decimal)oppSumAmount.get('total');
oppList = [Select Id, Name, convertCurrency(Opportunity.Amount), Opportunity.CloseDate, Opportunity.CurrencyIsoCode, Opportunity.SecretCode__c From Opportunity o where Id IN :selectedIdSet order by CloseDate desc];
oppListSize = oppList.Size();
System.debug('__oppLineList__'+oppList);
isOpen=false;
}
}
This is the JS file which is giving error:
http://invoicedetails.dev.cs16.force.com/faces/a4j/g/3_3_3.Finalorg.ajax4jsf.javascript.AjaxScript?rel=1339862070000
and error is giving in this line
var ask=actionUrl.indexOf('?')
what is wrong in my code. anybody please help me.

Please, post a controller code for processOnSelected method.
I can assume that this method doesn't have params or it is private.
Try to change
public void processOnSelected() {
...
}
to
public PageReference processOnSelected(string commandAtt) {
...
return null;
}

Related

Loading selected GridView Item in Popup using CallBacks with ASP.Net MVC

I still relatively new to ASP.Net and the concepts of communicating between client and server. I am using DevExpress tools but I believe this issue is more of a misunderstanding of the concept.
I have a GridView within a partial view that is loaded via an Action #Html.Action('MessageGridView'). This works no problem and data is loaded fine with the index and a returned model.
#Html.DevExpress().GridView(settings =>
{
settings.Width = System.Web.UI.WebControls.Unit.Percentage(100);
settings.Name = "preparedMessagesGrid";
settings.CallbackRouteValues = new { Controller = "Messages", Action = "MessagesGridView" };
settings.KeyFieldName = "Id";
settings.SettingsBehavior.AllowSelectByRowClick = true;
settings.SettingsBehavior.AllowSelectSingleRowOnly = true;
settings.ClientSideEvents.Init = "GridViewInit";
settings.ClientSideEvents.SelectionChanged = "OnSelectionChanged";
settings.ClientSideEvents.BeginCallback = "OnBeginCallback";
settings.SettingsBehavior.AllowEllipsisInText = true;
settings.PreRender = settings.Init = (sender, e) =>
{
MVCxGridView gridView = sender as MVCxGridView;
gridView.Selection.SelectAll();
};
settings.Columns.Add("Name");
settings.Columns.Add("Description");
}).Bind(Model.preparedMessages).GetHtml()
What I am trying to achieve is when the user selects the row I wish the data to be loaded into the popup control when clicked. Is there a way I can set the parameters dynamically for the popup control callback?
#Html.DevExpress().PopupControl(settings =>
{
settings.Name = "pcModalMode";
settings.Width = 100;
settings.AllowDragging = true;
settings.CloseAction = CloseAction.CloseButton;
settings.CloseOnEscape = true;
settings.PopupAnimationType = AnimationType.None;
settings.HeaderText = "Login";
settings.Modal = true;
settings.PopupHorizontalAlign = PopupHorizontalAlign.WindowCenter;
settings.PopupVerticalAlign = PopupVerticalAlign.WindowCenter;
settings.CallbackRouteValues = new { Controller = "Messages", Action = "Load", new { id = THIS NEEDS TO BE SELECTED ID VALUE} };
settings.LoadContentViaCallback = LoadContentViaCallback.OnFirstShow;
}).GetHtml()
It works if I set the value static so I'm one step away from getting this working. What I have researched is that I can get the values from the GridView in javascript using the selection changed event.
function OnSelectionChanged(s, e) {
s.GetSelectedFieldValues("Id", GetSelectedFieldValueCallback);
}
I can then retrieve this value but can I set this to my popup control or am I misunderstanding being relatively new and possibly I could do this server side for when the ViewGrid callback is performed, then set it server side with a session of some sort?
You're just one step away to get currently selected grid value with this function:
function OnSelectionChanged(s, e) {
s.GetSelectedFieldValues('Id', GetSelectedFieldValueCallback);
}
What you need to do is declaring GetSelectedFieldValueCallback method as this (I got from a test that selectedValue contains array with single value for single grid row selection, use zero index to assign the value):
var id; // a global variable set to hold selected row key value from grid
function GetSelectedFieldValueCallback(selectedValue) {
if (selectedValue.length == 0)
return;
id = parseInt(selectedValue[0]);
pcModalMode.PerformCallback();
}
Then setting BeginCallback on PopupControl helper as given below, note that for DevExpress HTML helpers you can use customArgs in client-side to pass action method parameters instead of using CallbackRouteValues with id parameter:
#Html.DevExpress().PopupControl(settings =>
{
settings.Name = "pcModalMode";
// other stuff
settings.CallbackRouteValues = new { Controller = "Messages", Action = "Load" };
settings.ClientSideEvents.BeginCallback = "OnPopUpBeginCallback";
settings.ClientSideEvents.EndCallback = "OnPopUpEndCallback";
// other stuff
}).GetHtml()
// JS function for popup callback
function OnPopUpBeginCallback(s, e) {
e.customArgs["id"] = id; // this sends 'id' as action method parameter to `Load` action
}
// Optional end callback
function OnPopUpEndCallback(s, e) {
if (!pcModalMode.IsVisible())
pcModalMode.Show();
}
Finally, let's putting them all together in view & controller code:
View
<!-- View page -->
<script type="text/javascript">
var id;
function OnSelectionChanged(s, e) {
s.GetSelectedFieldValues('Id', GetSelectedFieldValueCallback);
}
function GetSelectedFieldValueCallback(selectedValue) {
if (selectedValue.length == 0)
return;
id = parseInt(selectedValue[0]);
pcModalMode.PerformCallback();
}
function OnPopUpBeginCallback(s, e) {
e.customArgs["id"] = id;
}
function OnPopUpEndCallback(s, e) {
if (!pcModalMode.IsVisible())
pcModalMode.Show();
}
</script>
GridView (partial view)
#Html.DevExpress().GridView(settings =>
{
settings.Name = "preparedMessagesGrid";
// other stuff
settings.ClientSideEvents.SelectionChanged = "OnSelectionChanged";
}).Bind(Model.preparedMessages).GetHtml()
Popup (partial view)
#Html.DevExpress().PopupControl(settings =>
{
settings.Name = "pcModalMode";
// other stuff
settings.CallbackRouteValues = new { Controller = "Messages", Action = "Load" };
settings.ClientSideEvents.BeginCallback = "OnPopUpBeginCallback";
settings.ClientSideEvents.EndCallback = "OnPopUpEndCallback";
// other stuff
}).GetHtml()
Controller
public class Messages : Controller
{
public ActionResult MessagesGridView()
{
// grid view populating data code lines here
return PartialView("_GridView", data);
}
public ActionResult Load(int id)
{
// code lines to find ID here
return PartialView("_ModalPopup", model);
}
}
References:
(1) Display GridView Row Details in PopupControl Window
(2) How to display detail data within a popup window (MVC)
(3) ASPxClientGridView.GetSelectedFieldValues (DevExpress Documentation)
(4) MVCxClientBeginCallbackEventArgs.customArgs (DevExpress Documentation)

Updating certain Primefaces Diagram Element

I am trying since 2 days to solve a issue I got with my primefaces diagram implementation.
I want on "mouseover" the diagram elements, highlight other elements that are connected with that element.
I have it working, but ONLY if I update the whole diagram/form when I update the elements.
I have two problems with that approach.
First with the constant updates on mouseover all the binding on mouseenter and other stuff, gets reset so I have the event fire all the time although I just entered. Also 80% of the time I dont catch the mouseleave / hover leave event because of the constant calls.
Also I cant scroll the diagram anymore as the constant updates on mouseover would reset the scroll. ;-)
So I tried to only update the diagram elements I actually changed on mouseover, but I could not find a way that worked for me...
I tried just updateing the element via primefaces RequestContect.update
I used all variations on the Id like:
1-0201
diagram-1-0201
diagram:diagram-1-0201
I tried a javascript query from primefaces execute. I got a ui cant be resolved error on that one. Although the same query works on the xhtml. I also couldnt figure out that error. Although I dont think it would help, as the same code doesnt work when executed in the html file aswell.
I tried just saving the connections in a diagram element value and then accessing this value via hidden input on the elements. I got the ids for the connected elements in my javascript but I could not update the elements via javascript aswell. "inside" (leftover commented code) was the variable I had for the hidden inputs that were referenced on the Element variable that stored the connections)
I got both the list and the single connected ids in javascript but couldnt manage to update the elements.
I am not that experienced in javascript. I used it for the first time a few days ago.
So how do I update the style of certain elements in the primefaces diagram without reloading the hole diagram?
There must be a very easy way to do it or an easy way to fix my approaches I just cant see.
It is working if I update the whole diagram as I said, but I cant do that on mouseover for obvious reasons.
I am using primefaces 6.0 with a apache tomcat 8.5
Picture of the setup with ids: http://i.imgur.com/9yTEabE.png
Picture of the javascript log for the events: http://imgur.com/mCgf0BU
my xhtml file:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:p="http://primefaces.org/ui"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<p:panelGrid columns="2" styleClass="borderless">
<h:graphicImage name="images/logo.gif" />
<h:outputLabel styleClass="h1" value="Diagram Viewer" />
</p:panelGrid>
<f:metadata>
<f:viewAction action="#{dataManager.onLoad}" />
</f:metadata>
</h:head>
<h:body>
<h:form id="tabMenuForm">
<p:menubar styleClass=".ui-menu .ui-menuitem-link"
model="#{dataManager.menuModel}" />
</h:form>
<h:form id="diagramForm">
<p:dialog widgetVar="statusDialog" modal="true" draggable="false"
closable="false" resizable="false" showHeader="false">
<p:graphicImage value="#{resource['images/defaultLoader.gif']}" />
</p:dialog>
<p:tooltip />
<p:diagram id="diagram" value="#{dataManager.model}"
styleClass="borderless" style="#{dataManager.diagramStyle}" var="el">
<f:facet name="element" id="diagramElement" widgetVar="element">
<h:outputLabel>
<p:commandLink
actionListener="#{tooltipManager.onElementClickedTwo()}"
styleClass="commandRemover">
<f:param name="selected" value="#{el.id}" />
<div class="elID">
<h:outputText value="#{el.id}" />
</div>
<div class="elName">
<h:outputText value="#{el.name}" sytleCLass="elName" />
</div>
</p:commandLink>
</h:outputLabel>
<!-- <h:outputText value="#{el.role}" style="display: inline; align-items: right; margin-top:0em;"/> -->
</f:facet>
</p:diagram>
<p:remoteCommand name="elementMouseOver"
actionListener="#{dataManager.onElementMouseOver}" />
<p:remoteCommand name="elementMouseOut"
actionListener="#{dataManager.onElementMouseOut}" />
<h:inputHidden id="someId" value="#{dataManager.selectedId}" />
<script type='text/javascript'>
$('.ui-diagram-element').hover(function(ev) {
var id = $(this).attr('id');
console.log(ev);
var id = $(this).attr('id');
//var inputs = $(this).find('input');
//console.log('INSIDE!' + inputs);
//var input = inputs[0].val();
//var val = $(input).val();
//console.log('VAL: ' + val);
//console.log('INSIDE!' + input);
//var string = '#diagramForm\\:diagram-' + input;
//$(string).addClass('ui-diagram-element-predecessor');
//+ val[i]));
elementMouseOver([ {
name : 'elementId',
value : id
} ]);
//console.log(val);
}, function(ev) {
//***leave***//
var id = $(this).attr('id');
});
</script>
Important part of the Bean:
private DiagramNode selected;
private String selectedId = "x";
private List<String> selectedList = new ArrayList<String>();
public String getSelectedId() {
return selectedId;
}
public void setSelectedId(String selectedId) {
this.selectedId = selectedId;
}
public List<String> getSelectedList() {
return selectedList;
}
public void setSelectedList(ArrayList<String> selectedList) {
this.selectedList = selectedList;
}
public void onElementMouseOver() {
String input = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("elementId");
System.out.println("DataManager: Input: " + input);
String[] mouseoverIdSplit = input.split("-", 2);
if (mouseoverIdSplit.length < 2)
return;
System.out.println("DataManager: Mouseover:" + mouseoverIdSplit[1]);
selected = DataLoader.WPCPTaskRows.get(mouseoverIdSplit[1]);
selectedId = mouseoverIdSplit[1];
selectedList = selected.connections;
for (String id : selected.connections) {
System.out.println("Setting StyleClass for " + id);
String elementToUpdate = "diagramForm:diagram-" + id;
System.out.println(elementToUpdate);
RequestContext.getCurrentInstance().update(elementToUpdate);
RequestContext.getCurrentInstance()
.execute("$('#" + elementToUpdate + "').addClass(ui-diagram-element-predecessor);");
}
// RequestContext.getCurrentInstance().update("scriptBean");
// RequestContext.getCurrentInstance().update("someId");
RequestContext.getCurrentInstance().update("diagramForm");
RequestContext.getCurrentInstance().update("diagram");
}
public class DiagramElement implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private String id;
private String role;
private String predecessor;
private List<String> predecessorList;
public DiagramElement() {
}
public DiagramElement(String name, String id, String role, String predecessor, List<String> predecessorList) {
this.name = name;
this.id = id;
this.role = role;
this.predecessor = predecessor;
this.predecessorList = predecessorList;
}
+getter and setter
After more then 10 hours of insanity I FINALLY got it working.
I connected the strings for the ID in javascript not correctly.
Also I had to add 3 \\ to the string, because 1 was swallowed as a escape and I needed 2 for a javascript function to find the element with a ":" inside it.
Here is how I did it in the end:
<h:inputHidden value="#{el.predecessorList}" />
$('.ui-diagram-element').hover(
function(ev) {
var id = $(this).attr('id');
console.log(ev);
var id = $(this).attr('id');
var inputs = $(this).find('input');
console.log(inputs);
var input = inputs[1];
//var val = $(input).val();
//console.log('VAL: ' + val);
var array = input.value;
console.log(array);
var parsedArray = array.replace("[", "").replace("]",
"").replace(/\s/g, "").split(',');
for ( var pos in parsedArray) {
var str1 = '#diagramForm\\\:diagram-';
var str2 = parsedArray[pos];
console.log(str2);
var con = str1.concat(str2);
console.log(con);
$(con).addClass('ui-diagram-element-predecessor');
}
},
function(ev) {
//***leave***//
var id = $(this).attr('id');
console.log(ev);
var id = $(this).attr('id');
var inputs = $(this).find('input');
console.log(inputs);
var input = inputs[1];
//var val = $(input).val();
//console.log('VAL: ' + val);
var array = input.value;
console.log(array);
var parsedArray = array.replace("[", "").replace("]",
"").replace(/\s/g, "").split(',');
for ( var pos in parsedArray) {
var str1 = '#diagramForm\\\:diagram-';
var str2 = parsedArray[pos];
console.log(str2);
var con = str1.concat(str2);
console.log(con);
$(con).removeClass('ui-diagram-element-predecessor');
}
});

ASP.NET MVC -Refresh CodeMirror editor onclick

I have a codemirror editor in a partial view and a list of files in the main view. I want to refresh the editor once a file name is clicked. I tried many solutions provided on StackOverflow and other websites but nothing worked , and This is my first time using Javascript so I can't figure out What am I doing wrong.
This is my code:
Controller:
public ActionResult Index()
{
StudentsCodes model = new StudentsCodes();
model.Student = (Student)CurrentUser;
var user = UserManager.FindById(((Student)CurrentUser).InstructorID);
model.Instructor =(Instructor) user;
return View(model);
}
public PartialViewResult DevelopmentPartial (StudentsCodes path )
{
return PartialView(path);
}
Main view:
<script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script type="text/javascript" src="~/Scripts/jquery-3.1.1.js"></script>
<ul id="tree">
#foreach (var file in Directory.GetFiles(Server.MapPath("~/Content/" + Model.Student.UserName + "/CompilerProject/" + name)))
{
var filename = Path.GetFileName(file);
<li id="filelist" onclick="#(Model.path = "~/Content/" + Model.Student.UserName + "/CompilerProject/src/" + #filename)">
<span class="glyphicon glyphicon-file"></span>
#filename
/li>
}
<div id="partial">
#{
Html.RenderPartial("DevelopmentPartial",null);
}
</div>
<script>
$(document).ready(function () {
$("#filelist").click(function (e) {
#{Html.RenderAction("DevelopmentPartial", Model);
}
});
});
</script>
partial view:
#using (Html.BeginForm())
{
var fileContents= "";
if (Model==null)
{
fileContents = "";
}
else
{
fileContents = System.IO.File.ReadAllText(Server.MapPath(Model.path));
}
#Html.TextArea("code", fileContents, new { id = "code" })
}
I can't assign ids for list elements since their number is unknown at compile time and it changes when the user adds or deletes a file, that's why most of the solutions provided didn't work . The result here was 3 editors overlapping and display the contents of the last file. And <li> items are non-clickable. What am I doing wrong in my code ?
Edit:
After updating the script as the following:
<script>
$(document).ready(function() {
$(".filelist").on("click",function (e) {
$("#partial").load('DevelopmentPartial');
});
});
</script>
It refreshes the partial view but the editor is always empty, and the Model is always null. Is it wrong to update the Model using "onclick"?
In case someone faced the same problem, I solved it by changing id to class at the list, then by using this script:
<div id="partial">
#{
Html.RenderAction("DevelopmentPartial", new { path1 = Model.path});
}
</div>
<script>
$(document).ready(function () {
$('.filelist').on('click', function (e) {
alert('Im clicked on filePath = ' + $(this).attr('value'));
var filePath = $(this).attr('value'); //value is attribute set in Html
$('#partial').load('DevelopmentPartial', { path1: filePath });
});
});
</script>
And the controller:
public PartialViewResult DevelopmentPartial(string path1)
{
modelSC.path = path1;
return PartialView(modelSC);
}
where modelSC is a global variable in the controller.

Upload Multiple Image using multiple file control in asp.net mvc 4.0 (angular js)

I am using Visual Studio 2012 Express with Framework 4.5 MVC.
I am also using Angular Js for the first time.
I have a view page that contains the multiple browse (file) button that will be use for upload single image by selecting each of them individually with my form data.
The problem is that by using submit button I am not able to get the images but I got the form data.
I want to get the images with the form data using Angular js.
I have already referred below posts but not getting the solution:
LINK 1
LINK 2
Please anyone help me to solve out this problem, would be appreciated.
I have a sample code for the uploading of multiple image using angularjs.
This link might help you: https://jsfiddle.net/n9tL7cdr/1/
<div ng-app="test">
<div ng-controller="UploadCtrl">
<table>
<tr ng-repeat="i in [1, 2, 3, 4]">
<td>{{i}}</td>
<td>
<input type="file" name="file" onchange="angular.element(this).scope().photoChanged(this.files)" /> </td>
<td>
<img ng-src="{{ image[$index].dataUrl }}" height="50px" />
</td>
</tr>
</table>
</div>
CONTROLLER:
angular.module('test', []);
angular.module('test').controller('UploadCtrl', function ($scope, $timeout) {
// Variable for image.
$scope.image = {
dataUrl: []
};
$scope.fileReaderSupported = window.FileReader != null;
$scope.photoChanged = function (files, index) {
if (files != null) {
var file = files[0];
var index = this.$index; // index of image.
if ($scope.fileReaderSupported && file.type.indexOf('image') > -1) {
$timeout(function () {
var fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = function (e) {
$timeout(function () {
$scope.image[index] = {dataUrl: e.target.result}; // Retrieve the image.
});
}
});
}
}
};
});
Here i find the solution using HttpPostedFileBase and Form Collection.
public ActionResult AddImageUpload(IEnumerable<HttpPostedFileBase> files,FormCollection fc )
{
ImageUpload IU = new ImageUpload();
IU.MaterialId = Convert.ToInt32((fc["MaterialId"]).Replace("number:",""));
IU.CategoryId = Convert.ToInt32((fc["CategoryId"]).Replace("number:", ""));
string tr = fc["hdnSub"].ToString();
string result = null;
string Message, fileName, actualFileName;
Message = fileName = actualFileName = string.Empty;
bool flag = false;
//HttpPostedFileBase f= IU.ImageP;
string[] SubAssemblyId = (tr.Split(','));
int i = 0;
string databaseid = null;
for (int j=0 ; j<files.Count(); j++)
{
var fileContent = Request.Files[j];
if (fileContent.FileName != "")
{
databaseid = SubAssemblyId[i];
string fn = DateTime.Now.ToShortDateString().Replace("/", "") + DateTime.Now.TimeOfDay.Hours + DateTime.Now.TimeOfDay.Minutes + DateTime.Now.TimeOfDay.Seconds + DateTime.Now.TimeOfDay.Milliseconds + Path.GetExtension(fileContent.FileName);
fileName = fn;
try
{
if (fileContent != null && fileContent.ContentLength > 0)
{
var inputStream = fileContent.InputStream;
var path = Path.Combine(Server.MapPath("/Images/Product/"), fn);
using (var fileStream = System.IO.File.Create(path))
{
inputStream.CopyTo(fileStream);
}
}
}
catch (Exception)
{
}
}
i++;
}
return RedirectToAction("ImageUpload");
}

Jeditable Problem in castle monorail

I am trying to use Jeditables (http://www.appelsiini.net/projects/jeditable) in my first castle monorail mvc application
I managed to have the textbox appearing and to the the ajax call, my problem is now that after the ajax call the edited text returs is not changes and i can t get the response after the call
this is my page
<head>
<link href="../../Styles/Main.css" rel="stylesheet" type="text/css" />
<script src="../../JavaScript/jQuery1.4.2.js" type="text/javascript"></script>
<script src="../../JavaScript/EditInLine.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.editable').editable('/Home/Save', {
id : 'editableId',
name : 'editableText',
type : 'textarea',
cancel : 'Cancel',
submit : 'OK',
indicator : '<img src="img/indicator.gif">',
tooltip : 'Click to edit...',
width : '200',
style : 'display: inline',
callbac : function(value, settings) {
alert(value);
return value;
}
});
});
</script>
</head>
<body>
<label id='1' class='editable '>Some text</label>
</body>
</html>
and this my controller
using Castle.MonoRail.Framework;
using System;
using EditInLine.Model.Interfaces;
using EditInLine.Model;
namespace EditInLine.Controllers
{
[Layout("Default"), Rescue("Default")]
public class HomeController : SmartDispatcherController
{
private EditableElement editableElement;
private EditableElement EditableElement
{
get
{
if (Session["EditableElement"] == null)
{
Session["EditableElement"] = new EditableElement { Id = 1, Text = "Some text", CssClass = "editable" };
}
return (EditableElement)Session["EditableElement"];
}
}
public void Index()
{
PropertyBag["IsAdmin"] = true;
PropertyBag["element"] = EditableElement;
}
public void Save()
{
var elementId = Convert.ToInt32(Request.Form["editableId"]);
var text = Request.Form["editableText"];
var element = new EditableElement { Id = elementId, CssClass = "editable", Text = text };
Session["EditableElement"] = element;
}
}
}
thanks for you help
The problem with Save() was that you did not return a string to the browser. Easily fixed with RenderText() call. You should also be using parameter binding instead of messing with Request.Form:
public void Save(int editableId, string editableText)
{
var element = new EditableElement { Id = editableId, CssClass = "editable", Text = editableText};
Session["EditableElement"] = element;
RenderText(editableText);
}
I found the solution
public void Save()
{
var elementId = Convert.ToInt32(Request.Form["editableId"]);
var text = Request.Form["editableText"];
var element = new EditableElement { Id = elementId, CssClass = "editable", Text = text };
Session["EditableElement"] = element;
Response.Write(text);
CancelView();
}

Categories

Resources