How use Kendo UI Editor in asp.net mvc3 with razor? - asp.net-mvc-3

I'm using editor from Kendo UI, so I have big problem.
I don't know how display items which are returned by editor.
Editor convert something like:
<img src="someurl" />
to:
lt;p><img src="someurl"/></p>
and I keep converted string in database, and try display it with:
#Html.Raw(item.description)
where description is string returned by kendo.
So I have no idea how display it correctly in my View
Any help would be appreciated.

There is an option of the KendeUI editor called encoded which configures whether the Editor should submit encoded HTML tags or not.
The default value for encoded is true
If you wan't to store the unencoded text use this sniplet when creating your editor:
$("#Editor").kendoEditor({
encoded: false
});
But because you are not sending encoded text to the server the Asp.net request validator kicks in and it will abort your request.
If you are using strongly typed views what you can do is to use the AllowHtmlAttribute on your model property:
View:
#model MyModel
#using(Html.BeginForm("SomeAction", "SomeController"))
{
#Html.TextAreaFor(m => m.Editor)
<input type="submit" value="Save" />
}
<script type="text/javascript">
$(function(){
$("#Editor").kendoEditor({
encoded: false
});
});
</script>
Model:
public class MyModel
{
[AllowHtml]
public string Editor { get; set; }
}
Controller action
public ActionResult SomeAction(MyModel myModel)
{
//Save to db, etc.
}
You also need to set the following in your web.config or this attribute won't have effect in .NET 4.0:
<httpRuntime requestValidationMode="2.0"/>

I found this solution for MVC:
in View
<div class="editor-field">
#(Html.Kendo().EditorFor(model => model.HtmlField).Encode(false))
#Html.ValidationMessageFor(model => model.HtmlField)
</div>
in model:
[DataType(DataType.Html)]
[AllowHtml]
public string HtmlField{ get; set; }
That was enough

Simplier way to do it is make changes in controller, no in view and model. So:
View
$("#Editor").kendoEditor();
Model
public class MyModel
{
public string Editor { get; set; }
}
Controller
Editor = Server.HtmlDecode(Editor);
HtmlDecode

The editor templates generated from the .NET Wrappers aren't working any more. Here is a fix.
http://pknopf.com/blog/kendo-ui-editor-templates-for-asp-net

Related

MVC3: button to send both form (model) values and an extra parameter

In an MVC3 project, i use an Html.BeginForm to post some (model-)values. Along with those i want to send an extra parameter that is not part of the form (the model) but in the ViewBag. Now, when i use a Button (code in answer here: MVC3 razor Error in creating HtmlButtonExtension), all the form values are posted but the extra parameter remains null. When i use an ActionLink, the parameter is posted but the form values are not :) Any know how i can combine the two? Thanks!
#Html.Button("Generate!", new { id = ViewBag.ProjectID })
#Html.ActionLink("Generate!", "Post", new { id = #ViewBag.ProjectID })
My advice would be to declare a new Object in your App.Domain.Model something like this
namespace App.Domain.Model
{
public class CustomEntity
{
public Project projectEntity { get; set; }
public int variableUsed { get; set; }
}
}
In your view you can acces them easily by using CustomEntity.projectEntity and CustomEntity.variableUsed.
Hope it helps
You can do something like below.
View code
#using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { #id = "frmId", #name = "frmId" }))
{
#*You have to define input as a type button not as a sumit. you also need to define hidden variable for the extra value.*#
<input type="hidden" name="hndExtraParameter" id="hndExtraParameter" />
<input value="Submit" type="button" id="btnSubmit" onclick="UpdateHiddenValue()" />
}
<script type="text/javascript">
function ValidateUser() {
$("#hndExtraParameter").val('Assignvaluehere');
$("#frmId").submit();
}
</script>
Controller Code
[HttpPost]
public ActionResult ActionName(Model model, string hndExtraParameter)
{
//Do your operation here.
}

ASP.NET MVC 3 Ajax.BeginForm and Html.TextBoxFor does not reflect changes done on the server

I'm using the Ajax.BeginForm helper in ASP.NET MVC3 to submit a form that replaces itself with new values in the form set on the server. However when I use helpers like Html.TextBoxFor I get the values that was submitted, not the values I inserted into the model on the server.
For example; I set SomeValue to 4 in my action and show it in a textbox. I change the value to 8, hit submit and would expect the value to be changed back to 4 in the textbox, but for some reason it stays 8. But if I output SomeValue without using Html helpers it says 4. Anybody have some clue about what is going on?
My controller:
public ActionResult Index(HomeModel model)
{
model.SomeValue = 4;
if (Request.IsAjaxRequest())
return PartialView(model);
return View(model);
}
public class HomeModel
{
public int? SomeValue { get; set; }
}
My View (please not that I have all the needed javascript in my layout page):
<div id="ajaxtest">
#using(Ajax.BeginForm(new AjaxOptions{ InsertionMode = InsertionMode.Replace,
UpdateTargetId = "ajaxtest", HttpMethod = "Post" })) {
#Html.TextBoxFor(model => model.SomeValue)
<input type="submit" value="Update" />
}
</div>
you can use
ModelState.Clear()
in your controller method to make the html helpers use your changed model. Otherwise they use the values from the form submit
Have a look at: Asp.net MVC ModelState.Clear
in your POST method you need to do
ModelState.Clear();
to reflect the changes made after the post

asp.net MVC 3 - JQuery ajax $.get return <nonscript> reCaptcha instead of actual html in partial view

This problem is kind of difficult to explain, but I'll do my best.
I'm simply trying to render the reCaptcha input on a form that is embedded inside a partial view.
Here's how I'm obtaining the partial view with JQuery $.get:
GetAndRenderPartialContent: function (url, obj) {
$.get(url, function (data) {
obj.replaceWith(function () {
var content = "<div id=\"" + obj.attr('id') + "\">" + data + "</div>";
return content;
});
});
}
This works great as a JQuery extension method.
The URL that's passed in to this method is simply a controller route that returns a partial view like this:
public ActionResult GetSomeContent()
{
var model = new SomeModel();
// set modal values
// Finally return partial view
return PartialView("_MyPartialView", model);
}
This works great. It even renders form values bound to the model.
The problem is only with reCaptcha. In my view I have this line to render the reCaptcha:
#Microsoft.Web.Helpers.ReCaptcha.GetHtml(theme: "clean", publicKey: ConfigurationManager.AppSettings["reCaptcha:publicKey"], language: "en")
This works when I embed it directly in the parent view.However, when it is rendered from the partial view method, I get the following results:
<noscript>
<iframe frameborder="0" height="300px" src="http://www.google.com/recaptcha/api/noscript?k=[MY PUBLIC KEY REMOVED FOR DEMO]" width="500px"></iframe>
<br /><br />
<textarea cols="40" name="recaptcha_challenge_field" rows="3"></textarea>
<input name="recaptcha_response_field" type="hidden" value="manual_challenge" />
</noscript>
It appears that the PartialView method is HtmlEncoding the output from the reCaptcha, but not the other form elements that are embedded in the form. Has anyone encountered this or have an elegant solution to this annoying problem that has taken up a couple of hours of my time?
The only solution I've been able to achieve is to render the reCaptcha in the parent view, hide it until the partial view page is called, then relocate it to the appropriate position in the form, which is not a desirable nor elegant solution.
Any help is appreciated.
Thanks.
* UPDATE **
I tried pasting the view code here but stackoverflow's editor kept rejecting the code. Suffice it to say, there is nothing unusual about the view. The model contains properties for binding such as:
[Required]
[Display(Name = "Email Address")]
public string Email { get; set; }
[Required]
[Display(Name = "Confirm Email Address")]
[Compare("Email", ErrorMessage = "Your email and confirmation email do not match.")]
public string ConfirmEmail { get; set; }
The form:
#using (Html.BeginForm("UpdateInfo", "MyAccount", FormMethod.Post, new { #id = "InfoForm" }))
Render the model items:
<div class="editor-label">
#Html.LabelFor(m => m.Email)
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.Email) #Html.ValidationMessageFor(m => m.Email)
</div>
Near the end of the form:
<fieldset id="reCaptchaFieldset">
<legend>Captcha Authorization</legend>
#ReCaptcha.GetHtml(theme: "clean", publicKey: System.Configuration.ConfigurationManager.AppSettings["reCaptcha:publicKey"])
</fieldset>
Try the following:
#Html.Raw(Microsoft.Web.Helpers.ReCaptcha.GetHtml(theme: "clean", publicKey: ConfigurationManager.AppSettings["reCaptcha:publicKey"], language: "en"))
Use the AJAX API part in this document:
http://code.google.com/apis/recaptcha/docs/display.html
Use this code in the partialView.

Custom attribute with dash in name using EditorFor/TextBoxFor/TextBox helpers

I am using Knockout-JS to bind properties in my view to my view model. Knockout-JS uses a custom attribute called 'data-bind' that you have to append to controls in which you want to be bound to view model objects.
Example:
<input type='text' name='first-name' data-bind='value: firstName'/>
Notice the 'data-bind' attribute.
In my view rendering, I am having trouble rendering a textbox that has this attribute. I am aware the Html.EditorFor, Html.TextBoxFor, and Html.TextBox helpers all take an anonymous object that you can use to specify custom attributes. The only problem with this implementation is C# doesn't allow dashes as variable names, so this won't compile:
#Html.EditorFor(m => m.FirstName, new { data-bind = "value: firstName" });
The only thing I can think of is this (in view-model):
public class DataBindingInput
{
public string Value { get; set; }
public string DataBindingAttributes { get; set }
}
public class MyViewModel
{
...
public DataBindingValue firstName { get; set; }
....
}
And a view template called "DataBindingInput.cshtml":
#model DataBindingInput
<input type='text' data-binding='#Model.DataBindingAttributes' value='#Model.Value'>
The only trouble with this is I lose the automatic generation of the input name so it won't work on a post-back because the model binder has no idea how to bind it.
How can I make this work?
Thanks to Crescent Fish above, looks like you can just use underscores and MVC 3 will convert them to dashes since underscores aren't allowed in HTML attribute names.

Strongly Typed RadioButtonlist

I want to get some options (say payment method cash, credit card etc.) and bind these to radio buttons. I believe there is no RadioButtonList in MVC 3.
Also, once radios are bound I want to show the previously selected option to the user while editing the answer.
As always you start with a model:
public enum PaiementMethod
{
Cash,
CreditCard,
}
public class MyViewModel
{
public PaiementMethod PaiementMethod { get; set; }
}
then a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
and finally a view:
#model MyViewModel
#using (Html.BeginForm())
{
<label for="paiement_cash">Cash</label>
#Html.RadioButtonFor(x => x.PaiementMethod, "Cash", new { id = "paiement_cash" })
<label for="paiement_cc">Credit card</label>
#Html.RadioButtonFor(x => x.PaiementMethod, "CreditCard", new { id = "paiement_cc" })
<input type="submit" value="OK" />
}
And if you want some more generic solution which encapsulates this in a helper you may find the following answer helpful.
This is how I like to bind RadioButtonLists. The view model has a collection of my strongly typed objects. For example, maybe PaymentOptions is a code table. Along with the collection is a SelectedPaymentOptionKey (or Selected*Id if you prefix your primary keys with Id). Initially this key will just be default 0, but on postback, it will hold the value of the selected item.
public class PaymentSelectionVM
{
public ICollection<PaymentOption> PaymentOptions { get; set; }
public int SelectedPaymentOptionKey { get; set; }
}
public ViewResult PaymentSelection()
{
var paymentOptions = db.PaymentOptions.ToList();
return View(
new PaymentSelectionVM {
PaymentOptions = paymentOptions,
//This is not required, but shows how to default the selected radiobutton
//Perhaps you have a relationship between a Customer and PaymentOption already,
//SelectedPaymentOptionKey = someCustomer.LastPaymentOptionUsed.PaymentOptionKey
// or maybe just grab the first one(note this would NullReferenceException on empty collection)
//SelectedPaymentOptionKey = paymentOptions.FirstOrDefault().PaymentOptionKey
});
}
Then in the View:
#foreach (var opt in Model.PaymentOptions)
{
#*Any other HTML here that you want for displaying labels or styling*#
#Html.RadioButtonFor(m => m.SelectedPaymentOptionKey, opt.PaymentOptionKey)
}
The m.SelectedPaymentOptionKey serves two purposes. First, it groups the Radio buttons together so that the selection is mutually exclusive(I would encourage you to use something like FireBug to inspect the generated html just for your own understanding. The wonderful thing about MVC is the generated HTML is fairly basic and standard so it shouldn't be hard for you to eventually be able to predict the behavior of your views. There is very little magic going on here.). Second, it will hold the value of the selected item on postback.
And finally in the post handler we have the SelectedPaymentOptionKey available:
[HttpPost]
public ActionResult PaymentSelection(PaymentSelectionVM vm)
{
currentOrder.PaymentOption = db.PaymentOptions.Find(vm.SelectedPaymentOptionKey);
....
}
The advantage of this over using SelectListItems is you have access to more of the object's properties in the case that you are displaying a grid/table and need to display many values of the object. I also like that there are no hard coded strings being passed in the Html helpers as some other approaches have.
The disadvantage is you get radio buttons which all have the same ID, which is not really a good practice. This is easily fixed by changing to this:
#Html.RadioButtonFor(m => m.SelectedPaymentOptionKey, opt.PaymentOptionKey, new { id = "PaymentOptions_" + opt.PaymentOptionKey})
Lastly, validation is a bit quirky with most all of the radio button techniques I've seen. If I really needed it, I would wire some jquery up to populate a hidden SelectedPaymentOptionsKey whenever the radio buttons are clicked, and place the [Required] or other validation on the hidden field.
Another workaround for the validation problem
ASP.NET MVC 3 unobtrusive validation and radio buttons
This looks promising but I haven't had a chance to test it:
http://memoriesdotnet.blogspot.com/2011/11/mvc-3-radiobuttonlist-including.html
You should bind your options to SelectList in ViewModel and set Selected attribute to true for previously selected option

Resources