CKEditor html content lifecycle: asp net mvc case - c#

My content will be edited number of times.So i need to store result html to database and load it again when it is neccessary.Here is my current start implementation:
#using (#Html.BeginForm("EditArticle", "Admin", new { id = ViewData["id"] }))
{
<div id="editor"> </div>
<input type="submit" value="save changes" onclick = "setValue()" />
<input type ="hidden" id="value" name="html" />
}
<script>
var editor, html = 'Model.Text';
function createEditor() {
if (editor)
return;
var config = { width:"900px"};
editor = CKEDITOR.appendTo('editor', config,html);
}
function setValue() {
$("#value").val(editor.getData());
}
createEditor();
</script>
But I get eror with initialization html variable.So, could anyone show how correct encode / decode html?
EDIT
Here is data controller receives:
html = <p>ARTICLE 3</p>\r\n
Values like this I store in database and try insert again.

First things first, to fix your code syntactically, it should probably read something like:
var editor, html = '#Html.Raw(Model.Text)';
However, why not instead of dealing with the markup in JavaScript and having to escape and unescape it, dump it directly where it should go i.e.
<textarea name="editor1">#Html.Raw(Model.Text)</textarea>
<script>
CKEDITOR.replace( 'editor1' );
</script>
And then transform that textarea into your ckEditor? As per their basic example here: http://docs.ckeditor.com/#!/guide/dev_framed
Secondly, aside from that I am not sure what errors you are receiving with your controller, so you will have to post further details for me to help you beyond the above.
I hope this helps.

Related

Pass Data from View to Controller - with model

I need to pass some information from the View to the Controller.
Currently, I am doing something like the following:
var url = '#Url.Action((object)#ViewBag.CompID, "Print", "DataRecords")' + '?location=' + model.Location + '&startDate=' + model.StartDateTime + '&endDate=' + model.EndDateTime;
window.location.href = url;
I wanted to hide the location, startdate and end date from showing up in the browser url.
I was thinking about creating a model as shown below and sending the model to the Controller but not sure how to.
var model = {
Location: $('#Location :selected').val(),
StartDateTime: $("#StartDate").val(),
EndDateTime: $("#EndDate").val()
};
Note that in my case, I do not need to retrieve any data back as the Print method will do the printing.
I am open to accomplishing this besides using
window.location.href
How can this be done using AJAX as I do not need to return back to the view with any data as the Print method action will print the the appropriate view.
If you want to pass data from the front end to the back-end controller, you have two ways:
through a GET(passing parameters on the URL)
with a POST that you can do it via AJAX or simply putting your information inside a form with POST action to the method you want to hit in the controller
MVC will do the binding for you, all the information using the POST, for example, should be inside the form, then on the controller, you can create your model as the input and use the default MVC bindings.
My suggestion if you want to hide that information from the url is to do it via a post(inside a form with a submit), but anyways if you click on the Network tab of the browser in both cases you should see the parameters you are passing to your controller.
There are other ways to achieve the same thing as the use of the TempData dictionary, which keeps information for a roundtrip operation between the controller and the view, but I don't recommend to proceed this way, every time I use that as a backdoor to patch my problems I feel guilty
You can do this.
Controller
public class HomeController : Controller
{
public ActionResult HideQueryString()
{
return View("Tut143");
}
public ActionResult Print(string location, string startDate, string endDate)
{
//print here
return RedirectToAction("HideQueryString");
}
public ActionResult Tut143()
{
return View();
}
View:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Tut143</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function () {
$("#theButton").click(function () {
var model = {
Location: $('#Location :selected').val(),
StartDateTime: $("#StartDate").val(),
EndDateTime: $("#EndDate").val()
};
var url = '#Url.Action("Print", "Home")' + '?location=' + model.Location + '&startDate=' + model.StartDateTime + '&endDate=' + model.EndDateTime;
window.location.href = url;
})
})
</script>
</head>
<body>
<div>
<select id="Location">
<option value="Arizona">Arizona</option>
<option value="California">California</option>
<option value="Wyoming">Wyoming</option>
<option value="Delaware">Delaware</option>
</select>
<input id="StartDate" type="text" value="default startdate value" />
<input id="EndDate" type="text" value="default enddate value" />
<input id="theButton" type="button" value="Go" />
</div>
</body>
</html>

ASP.NET MVC Razor get textbox value

How can I get the value of a textbox using razor?
<div>
<input type="text" id="somevalue" name="somevalue" class="form-control"/>
<input type="button" value="Search" class="btn btn-success"/>
</div>
<ul id="ReportsList" class="nav">
#foreach (var item in Model){
var roomName= document.getElementByID('somevalue').value
if (item.roomName == roomName) {
<li class="errorItem">
<a href="#" class="list-group-item">
<i class="fa fa-warning fa-fw"></i> #Html.DisplayFor(modelItem => item.roomName)
<span class="pull-right text-muted small">#Html.DisplayFor(modelItem => item.roomCapacity) pers.
</span>
..........
}
Is it possible to get the value of the textbox using MVC Razor? Cause using the getElementByID doesn't seem to work in razor...
Don't be brought down by the down-ticks.
You are obviously new to Razor and Mvc & Javascript. You problem is that you are mixing a server-side language with a client-side language. Razor is a server-side language so you will not be able to access client-side code (ie html or javascript) using Razor. Razor is used to render html to the client browser. Think of the code that you see in a cshtml file as a template for the code that will become an html file. The javascript on the other hand will only run when it gets to the users browser.
Now, lets try to make some sense of your code.
<div>
<input type="text" id="somevalue" name="somevalue" />
<input type="button" value="Search" />
</div>
<ul id="ReportsList" class="nav">
#foreach (var item in Model)
{
var roomName= document.getElementByID('somevalue').value; // This is javascript code.
if (item.roomName == roomName) {
<li>
#Html.DisplayFor(modelItem => item.roomName)
#Html.DisplayFor(modelItem => item.roomCapacity)
</li>
}
}
</ul>
I removed the classes to make it more legible. The problem above is that you are trying to find a value to use with your razor code. That code is running before it gets to the browser so that won't work.
You cannot solve this problem using Razor. That means your DisplayFor's are going to be useless for your scenario.
You need javascript to solve the problem, so you will need to do away with the Razor Code. Assuming your Model has as list of object with the properties you created in your example, you could do something like this.
<script type="text/javascript">
var data = #(Html.Raw(Json.Encode(Model));
for(var o in data) {
var item = data[o];
// You need to create an element here and add it to the ul here
// You could use jquery.
}
</script>
Unfortunately, you have the wrong tools here.
To actually accomplish what you are trying to do you are going to be better off investing in some javascript frameworks. I suggest that you learn AngularJs to do this.
Concerning Organization of Javascript
As stated in the comments you can use a script tag in your cshtml file. Unfortunately, this is not your problem. I added a little bit of a way to organize your javascript as well.
your.cshtml file.
<script type="text/javascript">
.. getElementById in here and do something.
</script>
Better Organization Might Look Like This
Put the code in a javascript file. In this example the name is person.js. I am using a person example because it is an easy way to look at creating an usable object in javascript. In this case person is the object.
person.js
function Person() {
}
Person.prototype = {
// Sets the element with id = "nameId" to "Jim Bob"
setName: function() {
var element = document.getElementById("nameId");
// Now do something with it.
element.innerHTML = "Jim Bob"; // get some user input.
}
};
// You could initialize this as a global reference.
// I don't recommend this but it will be the easiest way for now.
var person = new Person();
Next, you would have to use it somehow. The simplest way to use it is not the best way.
<button id="setNameButton" onclick="person.setName()">Set Name</button>
Improved example using JQuery
This example will bind the event in an unobtrusive way (ie. you won't be mixing javascript and html).
function Person() {
this.initialize();
this.name = "Jim Bob";
}
Person.prototype = {
initialize: function() {
// get reference to this object.
var self = this;
// Set up the click for button.
$(document).on('click', "#setNameButton", function() {
// Set the name
self.setName();
});
}
// Sets the element to this.name field.
setName: function() {
var element = document.getElementById("nameId");
// Now do something with it.
element.innerHTML = this.name;
}
};

html form posting to mvc controller

I am trying to set up a simple login html page, whose action is sent to mvc controller on another of my sites. I have no problem setting up the page to do the post, and in the mvc controller I have my method that reads the form post. The problem is that I am not seeing my fields from the html form in the form collection.
Is there something special that I need to do to read a form post within a mvc controller method, if so what is that?
The is the form action markup from my page
<form action="http://reconciliation-local.sidw.com/login/launch" method="post">
User Name <input type="text" id="username"/><br/>
Password <input type="text" id="password"/>
<input type="submit" value="launch"/>
</form>
The controller method
[HttpPost]
public ActionResult launch(FormCollection fc)
{
foreach (string fd in fc)
{
ViewData[fd] = fc[fd];
}
return View();
}
When I step through the controller method code, I am not seeing anything in the formcollection parameter.
Post Html To MVC Controller
Create HTML page with form (don't forget to reference a Jquery.js)
<form id="myform" action="rec/recieveData" method="post">
User Name <input type="text" id="username" name="UserName" /><br />
Password <input type="text" id="password" name="Password"/>
<input type="submit" id="btn1" value="send" />
</form>
<script>
$(document).ready(function () {
//get button by ID
$('#btn1').submit(function () {
//call a function with parameters
$.ajax({
url: 'rec/recieveData', //(rec)= Controller's-name
//(recieveData) = Action's method name
type: 'POST',
timeout: '12000', (optional 12 seconds)
datatype: 'text',
data: {
//Get the input from Document Object Model
//by their ID
username: myform.username.value,
password: myform.password.value,
}
});
});
});
</script>
Then in The MVC Controller
controller/action
| |
1. Create Controller named rec (rec/recieveData)
Create View named rec.cshtml
Here is the controller:
public class recController : Controller
{
// GET: rec
string firstname = "";
string lastname = "";
List<string> myList = new List<string>();
public ActionResult recieveData(FormCollection fc)
{
//Recieve a posted form's values from parameter fc
firstname = fc[0].ToString(); //user
lastname = fc[1].ToString(); //pass
//optional: add these values to List
myList.Add(firstname);
myList.Add(lastname);
//Importan:
//These 2 values will be return with the below view
//using ViewData[""]object...
ViewData["Username"] = myList[0];
ViewData["Password"] = myList[1];
//let's Invoke view named rec.cshtml
// Optionaly we will pass myList to the view
// as object-model parameter, it will still work without it thought
return View("rec",myList);
}
}
Here is the View:
#{
ViewBag.Title = "rec";
}
<h2>Hello from server</h2>
<div>
#ViewData["Username"]<br /> <!--will display a username-->
#ViewData["Password"] <!-- will display a password-->
</div>
If you posted some code it would be much easier to help you, so please edit your question...
Make sure that your form's action has the correct address, that your method is specifying POST (method="POST") and that the input fields under your form have name attributes specified.
On the server side, try making your only parameter a FormCollection and test that the fields in your form posted through the debugger. Perhaps your model binding isn't correct and the FormCollection will at least show you what got posted, if anything.
These are just common issues I've seen. Your problem could be different, but we need to see what you're working with to be able to tell.
Try something like this:
cQuery _aRec = new cQuery();
_aRec.Sqlstring = "SELECT * FROM Admins";
DataSet aDS = _aRec.SelectStatement();
DataTable aDT = aDS.Tables[0];
foreach (DataRow aDR in aDT.Rows){
if (txtAdminUsername.Text == aDR[0].ToString()){
if (txtAdminPassword.Text == aDR[1].ToString()){
Session["adminId"] = aDR[0];
Response.Redirect("Admin.aspx");
return;
}
}
}
Make sure that your FormCollection object properties for username and password are defined properly.
I had to use the name attribute on the text tag, and that solved my problem, is now working like a charm.
You have to use Ajax to do that.. Whenever you want to "submit" from client side, you should use Ajax to update the server
Step 1 - you redirect your Ajax call to your action, but with your list of parameters in the query-string appended
$.ajax(url: url + "?" + your_query_string_parameter_list_you_want_to_pass)
Step 2 - add optional parameters to your Controller-action with the same names and types you expect to get returned by the client
public ActionResult MyControllerAjaxResponseMethod(type1 para1 = null,
type2 para2 = null,
type3 para3 = null, ..)
Know that the optional parameters have to be initialized, otherwise the Action itself will always ask for those
Here's where the "magic" happens though --> MVC will automatically convert the query-string parameters into your optional controller-parameters if they match by name
I was also looking for a good answer for this, --> i.e. - one that doesn't use q-s for that usage, but couldn't find one..
Kinda makes sense you can't do it in any other way except by the url though..

MVC C# application, Json data in model

This may seem strange, but I would like to have my model contain Json data, which I could then use javascript to render html with the contents. My code looks like the following -
My Controller -
public ActionResult Index()
{
Object myObject = FillMyObjectWithData();
string json = new JavaScriptSerializer().Serialize(myObject);
return View(json);
}
My View -
#model string /*Json data will be in the model*/
<div>
//standard html in here
</div>
<script>
$(document).ready(function() {
doCoolStuff(#Model);
});
</script>
I am getting the error - "Illegal characters in path."
What is the correct way to accomplish this?
The problem is in return View(json);
You are getting the wrong function overload View(string), that is the overload to get a view by name. Try:
return View((object)json);
Also you want the raw JSON without HTML encoding:
doCoolStuff(#Html.Raw(#Model));
Try:
#model string /*Json data will be in the model*/
<div>
//standard html in here
</div>
<script>
$(document).ready(function() {
var temp = #model;
doCoolStuff(temp);
});
</script>
What is your motivation for attempting it this way? If you really want to return json you may be better served making an ajax request after the view/page loads and using javascript/jquery to render your UI with. This would be a good candidate for KnockoutJS.

ASP.NET MVC & JQuery Dynamic Form Content

I would like to dynamically add fields to an ASP.NET MVC form with JQuery.
Example:
<script language="javascript" type="text/javascript">
var widgets;
$(document).ready(function() {
widgets = 0;
AddWidget();
});
function AddWidget() {
$('#widgets').append("<li><input type='text' name='widget" + widgets + "'/></li>");
widgets++;
}
</script>
<ul id="widgets">
</ul>
This works, but I was going to manually iterate the form values in the controller:
[AcceptVerbs("Post")]
public ActionResult AddWidget(FormCollection form)
{
foreach (string s in form)
{
string t = form[s];
}
return RedirectToAction("ActionName");
}
But it occurred to me when I send the user back to the Get Action in the Controller I will have to set the FormData with the values entered and then iteratively add the widgets with <% scripting.
What is the est way to do this in the current release (5 I believe)?
My solution could be something like this (pseudo-code):
<script language="javascript" type="text/javascript">
var widgets;
$(document).ready(function() {
widgets = 0;
<% for each value in ViewData("WidgetValues") %>
AddWidget(<%= value %>);
<% next %>
});
function AddWidget( value ) {
$('#widgets').append("<li><input type='text' name='widget" + widgets +
"'>" + value + "</input></li>");
widgets++;
}
</script>
<ul id="widgets">
</ul>
And in the controller:
[AcceptVerbs("Post")]
public ActionResult AddWidget(FormCollection form)
{
dim collValues as new Collection;
foreach (string s in form)
{
string t = form[s];
collValues.add( t )
}
ViewData("WidgetValues") = collValues;
return RedirectToAction("ActionName");
}
You can work out the details later
(sorry for mixing VB with C#, I'm a VB guy)
i might be missing the point here, but, do you need to actually post the data back to the controller via a form action? why not make an ajax call using jquery to post the data to the controller...or better yet a web service? send the data async and no need to rebuild the view with the data values sent in.
This works fine if the values are being consumed and never used again, however, if you plan on persisting the data and surfacing it through a the view, your model should really support the data structure. maybe a Dictionary<string, string> on the model.
I'm not a ASP.net developer but I know from PHP that you can use arrays as names for input fields
Ex:
<input type="text" name="widgets[]" />
<input type="text" name="widgets[]" />
You can then iterate through the post variable widgets as if it was an array of values.
No messing around with dynamicaly named variables etc.
As far as I understand the problem is to preserve the posted values in widgets.
I thik you can just render those widgest you wont to populate on the server during the View rendering.

Categories