I am using CKeditor in MVC 3 app.
Right now i am in need of saving text with HTML tags to DB, problem is that Ckeditors GetData() method returns raw format of data (http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.editor.html#getData)
I need a way to make that raw format to normal string with Html tags
View :
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>TextEditionViewModel</legend>
#Html.DropDownListFor(model=>model.Id, Model.Texts)
<div class="editor-label">
#Html.LabelFor(model => model.Text)
</div>
<div class="editor-field">
#Html.TextAreaFor((model => model.Text), new { #Id = "editor1" })
#Html.ValidationMessageFor(model => model.Text)
</div>
<script type="text/javascript">
CKEDITOR.replace('editor1');
</script>
<script type="text/javascript">
var editor_data = CKEDITOR.instances['editor1'].getData();
var url = '#Url.Action("EditText1", "Admin")';
var data = { CommentText: editor_data };
function Save() {
alert(editor_data);
$.post(url, { CommentText: editor_data }, function (result) {
});
};
$('#Id').change(function () {
var selectedText = $(this).val();
if (selectedText != null && selectedText != '') {
$.getJSON('#Url.Action("Text","Admin")', { Id: selectedText }, function (text) {
CKEDITOR.instances['editor1'].setData(text);
});
}
});
</script>
</fieldset>
<p>
<input type="button" value="Save" onclick="Save()"/>
</p>
}
If editor_data is set to Normal "Text" string everything works!
Controller
public ActionResult EditText1(String CommentText)
{
return null;
}
You could decorate your controller action with the [ValidateInput] attribute to allow POSTing HTML tags which is not authorized by ASP.NET by default:
[HttpPost]
[ValidateInput(false)]
public ActionResult EditText1(string commentText)
{
return null;
}
UPDATE:
The problem is related to the fact that the editor_data variable is not accessible in the Save method.
You could do this:
<script type="text/javascript">
function Save() {
var editor_data = CKEDITOR.instances['editor1'].getData();
var url = '#Url.Action("EditText1", "Admin")';
var data = { CommentText: editor_data };
$.post(url, data, function (result) {
});
}
...
</script>
Related
How can I pass the value of my textbox "R_endDate" from my VIEW to my controller ExportToExcel function using Url.Action ?
On my View: Index.cshtml
I have this textbox with value of date.
<div class="uk-form-row">
<label class="uk-form-label" for="R_endDate">Ending Date:</label>
<div class="uk-form-controls">
#Html.TextBoxFor(m => m.R_endDate, new { #class = "uk-form-small uk-text-left required", #maxlength = 12, #data_uk_datepicker = "{format: 'MM/DD/YYYY'}" })
</div>
</div>
I have this anchor tag with url action.
Export
On my Controller: MISReportController.cs
public FileContentResult ExportToExcel()
{
byte[] filecontent = ExcelExportHelper.ExportExcel(list, "Technology", true, strAddtional);
return File(filecontent, ExcelExportHelper.ExcelContentType, strTitle);
}
my scripts
error1
You can easily handle this using javascript/jquery.
UI:
<a id="aExportToExcel" href="#" class="uk-button uk-button-small uk-text-center uk-text-small ">Export</a>
Script:
<script type="text/javascript">
$(document).ready(function () {
$("#aExportToExcel").click(function () {
var param = $("input[name='R_endDate']").val();
var _url = '#Url.Action("ExportToExcel", "MISReportController", new { param = "XXX" })'; // Param is the example parameter name. Change as needed.
_url = _url.replace("XXX", param); // _url will contain your url string so you can just play with it as needed for your requirement.
window.open(_url, "_blank");
});
});
</script>
try using html helper beginform()
in index.cshtml
#using (Html.BeginForm("ExportToExcel", "MISReport")) {<div class="uk-form-row">
<label class="uk-form-label" for="R_endDate">Ending Date:</label>
<div class="uk-form-controls">
#Html.TextBoxFor(m => m.R_endDate, new { #class = "uk-form-small uk-text-left required", #maxlength = 12, #data_uk_datepicker = "{format: 'MM/DD/YYYY'},#name="date" })</div></div>}
in the controller
[HttpPost]public FileContentResult ExportToExcel(Datetime date){ .......
}
I'm still new to asp.net mvc, i want to delete list of partial view, the delete is working but i must reload the entire page to show the new list
What I want is the partial view show the new list after delete without load the entire page, so only the partial view is updated
Here is my code:
My view content some of partial view :
#model cc.Models.User
#{
Layout = "~/Views/Shared/_MemberLayout.cshtml";
}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="#Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js")" type="text/javascript"></script>
<body class="container body-content">
<div id="partialView1">
#Html.Action(...)
</div>
<div id="partialView2">
#Html.Action(...)
</div>
<div id="partialView4">
#Html.Action(...)
</div>
<div id="partialView3" class="col-md-8 col-sm-1">
#Html.Action("UserHistory", "User")
</div>
</body>
Here is my partial view for UserHistory I tried to use ajax but it's not work. I already tried to use
$(this).closest('.historyRow').remove();
and
$("a.deleteHistory").live("click", function () {
$(this).parents("div.historyRow:first").remove();
return false;
});
Here is my code :
#model cc.Models.UserHistory
#{
Layout = null;
}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="#Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js")" type="text/javascript"></script>
<div id="formHistory">
<div id="historyDetail">
<div id="editDataHistoryUser">
#foreach (var item in Model.History)
{
#Html.Partial("UserHistoryDetail", item)
}
</div>
#Html.ActionLink("Add Form", "AddUserHistory", null, new { id = "btnFormHistory" })
</div>
</div>
<script type="text/javascript">
$("#btnFormHistory").click(function () {
$.ajax({
url: this.href,
cache: false,
success: function (html) { $("#editDataHistoryUser").append(html); }
});
return false;
});
$('#formHistory').on('click', '.deleteHistory', function () {
var id = $(this).data('id');
if (id == 0) {
$(this).closest('.historyRow').remove();
//$("a.deleteHistory").live("click", function () {
// $(this).parents("div.historyRow:first").remove();
// return false;
//});
} else {
var url = '#Url.Action("DeleteUserHistory", "User")';
$.post(url, { ID: id }, function (response) {
if (response) {
$(this).closest('.historyRow').remove();
//$("a.deleteHistory").live("click", function () {
// $(this).parents("div.historyRow:first").remove();
// return false;
//});
}
}).fail(function (response) {
});
}
});
</script>
Here is my UserHistoryDetail Code :
#model cc.Models.IUserHistory
#{
Layout = null;
}
<div id="formUserHistoryDetail">
#using (Ajax.BeginForm("UserHistoryDetail", "User", new AjaxOptions { HttpMethod = "POST" }))
{
<div id="historyRow">
<div>#Html.LabelFor(model => model.IDHistory, new { style = "display:none;" })</div>
...
delete
</div>
}
</div>
And here is my JsonResult when button delete clicked :
[HttpPost]
public JsonResult DeleteUserHistory(string ID)
{
db.delUserHistory(ID);
return Json(true);
}
I still cannot find the solution for this , or maybe i used ajax in wrong way, any suggestion?
Let's assume that the DeleteUserHistory post url is '/[Controller]/': '/UserHistory'
$('.deleteHistory').click(function(){
var url = '/UserHistory';
$.ajax({
type: "POST",
url: url,
data: data,
success: onSuccessCallback
});
});
What you should really do is use WebApi to manage data and use the views to display.
As for the delete, use method type 'delete' instead of 'post'. Post should be used for "adds".
I have some issues with rendering a partial view using jquery. Even if it was asked more than once (here), I didn't found a solution that worked for me:
My view:
#model IEnumerable<OdeToFood.Models.RestaurantListViewModel>
#{
ViewBag.Title = "Home Page";
}
<form method="get" action="#Url.Action("Index")" data-otf-ajax="true" data-otf-target="#restaurantlist">
<input type="search" name="searchTerm" />
<input type="submit" value="Search By Name" />
</form>
#Html.Partial("_Restaurants", Model)
My partial view:
#model IEnumerable<OdeToFood.Models.RestaurantListViewModel>
<div id="restaurantList">
#foreach (var item in Model)
{
<div>
<h4>#item.Name</h4>
<div>#item.City, #item.Country</div>
<div>REviews: #item.CountOfReviews</div>
<hr />
</div>
}
</div>
otf.js:
$(function () {
var ajaxFormSubmit = function () {
var $form = $(this);
var options = {
url: $form.attr("action"),
type: $form.attr("method"),
data: $form.serialize()
};
$.ajax(options).done(function (data) {
var $target = $($form.attr("data-otf-target"));
$target.replaceWith(data);
});
return false;
};
$("form[data-otf-ajax='true']").submit(ajaxFormSubmit);
});
index action of my controller:
public ActionResult Index(string searchTerm = null)
{
var model =
_db.Restaurants
.OrderByDescending(r => r.RestaurantReviews.Average(a => a.Rating))
.Where(r => searchTerm == null || r.Name.StartsWith(searchTerm))
.Select(r => new RestaurantListViewModel
{
Id = r.Id,
Name = r.Name,
City = r.City,
Country = r.Country,
CountOfReviews = r.RestaurantReviews.Count()
}
)
.Take(10);
if (Request.IsAjaxRequest())
{
return PartialView("_Restaurants", model);
}
return View(model);
}
My issue is that nothing happens when I press search button. I've added an test alert like:
$.ajax(options).done(function (data) {
var $target = $($form.attr("data-otf-target"));
alert('test');
$target.replaceWith(data);
});
and the alert showed when I've clicked the search button, but in site nothing happens. Anyone knows what is my issue?
You have #restaurantlist as the target, whereas div id is actually restaurantList. Capital "L".
I am trying to do something like, i have an index view which has some tags on each on one when click i want to return a partial view and append it to the div in main index.cshtml view
my code i below
Index.cshtml
#model OyeAPI.Models.User
#{
object user = Session["userId"];
ViewBag.Title = "Index";
}
<link href="#Url.Content("~/Content/css/style.css")" rel="stylesheet"/>
<div class="main_Container">
#if (Session["userId"] == null) {
<div class="login_div">
#Html.Partial("~/Views/Shared/_signin.cshtml")
</div>
}else
{
<div style="height:100px;">
<p>OyePortal</p>
</div>
// <p>#Html.ActionLink("clickme", "callLogs", "contactWeb")</p>
<div style="position:relative; left:400px;">
<div>
<p id="contacts">Contacts</p> | <p id="callLogs">Call Logs</p> |
<p id="messages">Phone Messages</p> | <p >Groups</p>
</div>
<div id="container_inner_frame">
<h1>Welcome fuck it clickme </h1>
</div>
</div>
}
</div>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
#*<script src="#Url.Content("~/Scripts/jquery-1.10.2.js")" type="text/javascript"></script>*#4
<script type="text/javascript">
$("#contacts").on("click", function () {
$("#container_inner_frame").html('#Html.Partial("~/Views/Shared/_contacts.cshtml")');
});
$("#callLogs").on("click", function () {
$("#container_inner_frame").html('#Html.Partial("~/Views/Shared/_callLogs.cshtml")');
});
$("#messages").on("click", function () {
$("#container_inner_frame").html('#Html.Partial("~/Views/Shared/_Phonemessages.cshtml")');
});
</script>
shared View _callLogs.cshtml
#model OyeAPI.Models.CallLogs
#{
List<Model.CallLogsModel> ListCallLogs = (List<Model.CallLogsModel>)ViewData["Data"];
Int64 CallID = 0;
string callNumber = null;
string callDuration = null;
string callType = null;
string date = null;
string daytime = null;
}
<div class="main_Container">
<div>
<div>
<ul>
<li>Contact ID</li><li>Contact Name </li><li>Contact Number</li>
</ul>
</div>
#if (ListCallLogs != null)
{
foreach (var item in ListCallLogs)
{
CallID = item.CallId;
callNumber = item.PhoneNumber;
callDuration = item.CallDuration;
callType = item.CallType;
date = item.CallDate.ToShortDateString();
daytime = item.CallDayTime.ToShortTimeString();
<div>
<ul>
<li>#CallID</li><li>#callNumber </li><li>#callDuration</li><li>#callType</li><li>#date </li><li>#daytime</li>
</ul>
</div>
}
}
else
{
<p>Empty String list no messages</p>
}
</div>
</div>
Controller contactWeb function callLogs
[HttpPost]
[AllowAnonymous]
public ActionResult callLogs()
{
Int64 userID = Convert.ToInt64(Session["userId"]);
try
{
List<CallLogsModel> callModel = new List<CallLogsModel>();
ICallLogs callLogObject = new CallLogsBLO();
callModel = callLogObject.GetCallLogs(userID);
ViewData["Data"] = callModel;
}
catch (Exception e)
{
}
return PartialView("_callLogs", ViewData["Data"]);
}
But its not working, when i run the code before login it hit the _callLogs shared view first and after that it show the login screen and when i click the callLogs it dosen't display any thing. i my be missing something
Your approach is not right:
you are writing jquery event, you have to send an ajax call to an action and return partial view of CallLogs and then append it to container div.
do like this:
$("#callLogs").on("click", function () {
$("#container_inner_frame").load('#Url.Action("callLogs","YOurController")');
});
or like this:
$("#callLogs").on("click", function () {
$.ajax({
url: '#Url.Action("callLogs", "YourControllerName")',
success: function (response) {
$("#container_inner_frame").html(response);
}
error: function () {
alert("error occured");
}
});
});
If you use the jQuery unobtrusive Ajax library, you should be able to do something as simple as this to load content from a partial on a button/link click. Note that you need to have a controller which returns a PartialViewResult (this can then reference your view) :
#Ajax.ActionLink("Click Me", "Action", "Controller", new AjaxOptions{ InsertionMode=InsertionMode.InsertAfter, UpdateTargetId="MyTargetDivId"})
<div id="MyTargetDivId"></div>
Try this :
$("#callLogs").on("click", function () {
$.ajax({
url: '#Url.Action("callLogs", "YourController")',
type: 'get',
datatype: 'json',
success: function (data) {
$('div#container_inner_frame').html(data);
}
});
});
Here is the final, which works! Thanks to bob-the-destroyer.
I just had to change this :
<script>
$(function () {
$('#formSearch').ajaxForm(function (result) {
$('#divArefresh').fadeOut('slow').fadeIn("slow").load('/Feed/Search');
});
});
</script>
Into this :
<script>
$(function () {
$('#formSearch').ajaxForm(function (result) {
$('#divArefresh').fadeOut('slow').fadeIn("slow").load(result);
});
});
</script>
EDIT: I thought that this :
// In /Feed/Index.cshtml
#using (Html.BeginForm("Search", "Feed", FormMethod.Post, new { id = "formSearch" }))
{
<input type="text" id="search" name="search" />
<input type="submit" value="save"/>
}
<script>
$(function () {
$('#formSearch').ajaxForm(function (result) {
$('#divArefresh').fadeOut('slow').fadeIn("slow").load('/Feed/Search');
});
});
</script>
With this :
// In Controller/Feed/
public ActionResult Search(string search)
{
if (!String.IsNullOrEmpty(search))
return Content("Variable : " + search);
else
return Content(":(");
return Content("Pas ajax :(");
}
Would do the trick, but it isn't. It always shows ":(". I'm really lost.
//////////////////////
I just wonder how to make this. I've tried many ways but I really don't manage to do it.
It's pretty easy to understand what I want to do :
I have a div which contains all the informations I want to show :
<div id="divArefresh">
<div id="accordion-container">
#foreach (var i in #ViewBag.feedsItem)
{
... Things ....
}
</div>
</div>
And I want to make a « search function », like this :
<!-- le champs de recherche -->
#{var options2 = new AjaxOptions()
{
Url = Url.Action("Search", "Feed"),
LoadingElementDuration = 200000,
OnComplete = "divSearch",
HttpMethod = "GET"
};
using (Ajax.BeginForm(options2))
{
<input type="text" name="search" id="search" placeholder="Votre recherche"/>
<input type="submit" id="submit" value="chercher"/>
}
}
Here is my « divSearch »
function divSearch() {
$('#divArefresh').fadeOut('slow').fadeIn("slow").load('/Feed/Search');
}
When I submit something, it goes fine in my action :
public ActionResult Search(string search)
{
Users user = db.UserProfiles.Find(Session["id"]);
if (Request.IsAjaxRequest())
{
var wordSearched = Request["search"].ToString(); --> NULL
var feeds = (from u in db.Feed
where u.UsersId == user.UsersId
select u).ToList(); --> FINE
var feedsItems = from u in db.FeedsItem
where u.Title.Equals(wordSearched)
select u;
ViewBag.feedsItem = feedsItems.ToList();
return PartialView("Search", feeds);
}
return PartialView("Search");
}
BUT this :
Request["search"].ToString();
is always null when I try with the debugger. Even the « search » variable is null
If someone have an idea on how to make this work...
Kai23