Summernote and form submission in MVC c# - c#

I am using the summernote plugin for text box:
http://summernote.org/#/getting-started#basic-api
This is the form I have using summmernote:
<div class="modal-body" style="max-height: 600px">
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset class="form-horizontal">
<div id="textForLabelLanguage"></div>
<button type="submit" class="btn btn-primary">Save changes</button>
#Html.ActionLink("Cancel", "Index", null, new { #class = "btn " })
</fieldset>
}
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#textForLabelLanguage').summernote();
});
</script>
Now, In my controller, this is the code I have:
public ActionResult Create(UserInfo newInfo , [Bind(Prefix = "textForLabelLanguage")] string textForLabelLanguage)
{
//logic here
}
Now the problem is that textForLabelLanguage param is always null.
This happens because I have to pass $('#textForLabelLanguage').code(); into MVC when submiting the form but I have no idea how to do that!
How do I solve my problem?

I found my solution to the problem. This is how I am making the controller get the correct information:
<div class="modal-body" style="max-height: 600px">
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset class="form-horizontal">
<textarea name="textForLabelLanguage" id="textForLabelLanguage" />
<button type="submit" class="btn btn-primary">Save changes</button>
#Html.ActionLink("Cancel", "Index", null, new { #class = "btn " })
</fieldset>
}
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#textForLabelLanguage').summernote();
});
</script>
Basically, if I use a textarea with a name instead of an input or anything else, it works!
However, and be warned, even though this solution works, I then get a error in the controller saying:
A potentially dangerous Request.Form value was detected from the client
This happens because I am allowing HTML. But this is a problem for another question!

Please, use [AllowHTML]
There's a good article on MSDN
Request Validation in ASP.NET
"To disable request validation for a specific property, mark the property definition with the AllowHtml attribute:"
[AllowHtml]
public string Prop1 { get; set; }

similar to what was posted earlier you can use the HTML helper
#HTML.TextAreaFor( m=> m.text, new {#id = "textFor*Model*"})
instead of <textarea>

Related

File upload ASP.NET MVC in multiple submits form

I have a small tool that downloads reports based on the specified options. The download works well. And now, I want to also upload a file to the folder and then further use it.
The problem is that I already have one submit button on the form that is used for the download and when I am adding another button for the upload, only download is triggered.
I tried to resolve it using an #Html.ActionLink(), but no success. Is there any proper way to resolve the issue? I know that there is a possibility to capture the submit value and then check in one main ActionResult in the Controller and redirect to the respective ActionResult, but I don't want to do it, since there are too many POST Actions in one controller.
Here is my View - download.cshtml:
#using (Html.BeginForm())
{
<fieldset>
<div class="title">Click to download report</div>
<div class="field">
<input id="downloadBtn" type="submit" class="button" value="Download" />
</div>
</fieldset>
<fieldset id="Option_ClientInfo">
<div class="title">
Image
</div>
<div class="field">
<input type="file" name="ImageUpload" accept="image/jpeg" />
<p>#Html.ActionLink("Upload", "UploadImage", new { controller = "Home", enctype = "multipart/form-data"}, new { #class = "button" })</p>
</div>
</fieldset>
}
And the controller - HomeController.cs:
public partial class HomeController : Controller
{
// some functions
// ....
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadImage(HttpPostedFileBase imageFile)
{
string path = Path.Combine(this.GetImageFolder, Path.GetFileName(imageFile.FileName));
imageFile.SaveAs(path);
return null;
}
// additional POST functions for other forms
// ....
[HttpPost]
public ActionResult Download(Info downloadInfo)
{
// perform checks and calculations
return new reportDownloadPDF(downloadInfo);
}
}
Any suggestion in appreciated.
The solution is just separate upload and download functionalities using two forms so it wont conflict while submitting.
#using (Html.BeginForm())
{
<fieldset>
<div class="title">Click to download report</div>
<div class="field">
<input id="downloadBtn" type="submit" class="button" value="Download" />
</div>
</fieldset>
<fieldset id="Option_ClientInfo">
<div class="title">
Image
</div>
</fieldset>
}
#using (Html.BeginForm("UploadImage", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<fieldset>
<div class="field">
<input type="file" name="ImageUpload" accept="image/jpeg" />
<p>
<input id="uploadBtn" type="submit" class="button" value="Upload" />
</p>
</div>
</fieldset>
}
There is another issue as well. Image control name and Post Action method parameter name should be same.
So your upload image Post Action method will be:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadImage(HttpPostedFileBase imageUpload)
{
string path = Path.Combine(this.GetBasePath + "/img/tmp/", Path.GetFileName(imageFile.FileName));
imageFile.SaveAs(path);
return null;
}

#Html.DropDownList return null to controller

The DropDownList in my view shows the relevant options to choose, but no matter what i choose, the folders in the Controller get value null.
Why? How can i fix it so the folders in the Controller will get the chosen option from the DropDownList from the view?
P.S - I have no Model.
This is my Controller:
//POST: Home
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(IEnumerable<HttpPostedFileBase> file, string folder, IEnumerable<SelectListItem> folders)
{
// some code here
}
This is my view:
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken();
<div class="container">
<div class="form-horizontal">
<div class="form-group">
<p></p>
<label for="file">Upload Photo:</label>
<input type="file" name="file" id="file" accept="image/*" multiple="multiple"/>
</div>
<div class="form-group">
<div>
<label>Choose Album:</label>
#if (ViewBag.Folders != null)
{
#Html.DropDownList("folders", new SelectList(ViewBag.Folders as IEnumerable<SelectListItem>, "Value", "Text"), "--- Select Album ---", new { #class = "form-control" })
}
</div>
</div>
<div class="form-group">
<div>
<input type="submit" value="Upload" class="btn btn-default" />
</div>
</div>
</div>
</div>
}
Thanks.
in order to get the folder, give your dropdownlist the corresponding name ...
#Html.DropDownList("folders"...
will result in your DDL to have the name "folders" ... which will try to post back a single item... folders in your method is a IEnumerable<SelectListItem> ... the modelbinder is incapable to convert that ...
try
#Html.DropDownList("folder"...
note the missing s
now the name corresponds to the string folder parameter in your method... which the binder will most likely be able to bind for you...
if you debug errors like this, use the debugger to have a look at HttpContext.Request.Params, which will show you what was coming back when the request was made...
Parameter type should be changed from IEnumerable to String as view returns only selected item NOT collection.
//POST: Home
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(IEnumerable<HttpPostedFileBase> file, string folder, string folders)
{
// some code here
}
Just wanted to give another option. If you're able to leverage a client-side solution, then you could muscle this a bit with a hidden input value and JQuery.
Add a hidden input control:
<input name="selectedFolder" type="hidden" value="" />
Add some Jquery:
<script type="text/javascript">
$(function(){
$("#folders").on("change", function {
$("#selectedFolder").val($(this).text());
});
});
</script>
Thank you Sakthivel Ganesan, after changing the IEnumerable<SelectListItem> folders in the Controller to string folders, the only thing left to do is to change my Html.DropDownList Value to Text like this...
from :
#Html.DropDownList("folders", new SelectList(ViewBag.Folders, "Value", "Text"), "--- Select Album ---", new { #class = "form-control" })
To:
#Html.DropDownList("folders", new SelectList(ViewBag.Folders, "Text", "Text"), "--- Select Album ---", new { #class = "form-control" })

How I can use html tags for input and submit in asp.net mvc 5 without Html.BeginForm?

net mvc 5 application and for this I use bootstrap because it looks fine.
I don't want to use for an input and a searchbutton the
#using (Html.BeginForm("...
Can I control the html tags without this from my controller. For example here is my index.cshtml
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container">
<div class="row">
<h2>Suche</h2>
<div id="custom-search-input">
<div class="input-group col-md-12">
<input type="text" class=" search-query form-control" placeholder="Search" />
<span class="input-group-btn">
<button class="btn btn-danger" type="button">
<span class=" glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</div>
</div>
</div>
I want if I click on the Searchbutton I get a message with the text from the inputfield.
Here is the Controller:
public ActionResult Search(string value)
{
//listofUsers is a arraylist of all users that found^^
return View(listofUsers);
}
How I can do this? :)
Add a div to show the result:
<div id="custom-search-input">
<div class="input-group col-md-12">
<input type="text" class=" search-query form-control" placeholder="Search" />
<span class="input-group-btn">
<button class="btn btn-danger" type="button">
<span class=" glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</div>
<div class="custom-search-result"></div>
Then in a script tag or a linked js file:
$(document).ready(function () {
$('.custom-search-input').each(function () {
var sinput = $(this);
var svalue = sinput.find('input');
var sresult = sinput.next('.custom-search-result');
sinput.find('button').click(function () {
$.ajax({
url: '/ControllerName/Search?value=' + svalue.val(),
type: 'GET'
}).done(function (result) {
sresult.html(result);
});
});
});
});
This is a basic example with no error handling.
First I highly recommend reading Philip Walton (Google) - Decoupling your HTML, CSS and Javascript, it's extremely good.
Here how I would use MVC to it's full potential.
Model:
// Extensible Programming
// Using a string limits additional features
// Future proofing via a class that takes 2 minutes to create
public class GlobalSearch
{
public string SearchTerms { get; set; }
}
View:
#Model GlobalSearch
<div class="container">
<div class="row">
<h2>Suche</h2>
<div id="custom-search-input">
#using (Html.BeginForm("Search"))
{
<div class="input-group col-md-12">
#Html.TextBoxFor(m => m.SearchTerms, new {
#class="search-query form-control",
placeholder="Search" })
<span class="input-group-btn">
<button class="btn btn-danger" type="button">
<span class=" glyphicon glyphicon-search js-form-submit"></span>
</button>
</span>
</div>
}
</div>
</div>
</div>
Controller:
// Strongly Typed Class is Returned
public ActionResult Search(GlobalSearch search)
{
return View(listofUsers);
}
The following script will require this fantastic script called form2js which correctly converts any strongly-typed forms generated by MVC (arrays, lists etc) into Json that will be ModelBinded correctly.
$(document).ready(function() {
('.js-form-submit').on('click', function() {
var $form = $(this).closest('form');
var json = form2js($form);
var ajaxSettings = {
url: $form.attr('action'),
type: $form.attr('method'),
data: json,
contentType: "application/json",
}
$.ajax(ajaxSettings)
.done()
.always()
.fail();
});
});
Of course this could be easily abstract into it's own javascript class/namespace that returns the promise and reusable on any form that simply has a button with the class js-form-submit instead of continually rewriting $.ajax over and over again each time for different forms.

MVC Ajax.BeginForm and Content Security Policy

To prevent cross side scripting i implement CSP to one of my applications. At moment i´m reconfigure all html classes, so that javascript always comes from my server.
Now i found a page with an Ajax.BeginForm and always get the error "Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self'"." if i want to submit the form and update the view.
Can anybody help me, where the problem is?
Here is my html classes (shorted):
UserInformation.cshtml:
<div id="OpenAccountInformation">#Html.Action("OpenAccountInformation")</div>
</div>
AccountInformation.cshtml:
#Scripts.Render("~/Scripts/bundles/ManageUsers/AccountInformation")
#model Tumormodelle.Models.ViewModels.AzaraUserModel
<input type="hidden" value="#ViewBag.Editable" id="EditableUserInformation">
<div id="Editable">
#using (Ajax.BeginForm("EditUser", "ManageUsers", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "OpenAccountInformation", HttpMethod = "post", }))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(m => m.UserID)
<div>
<div>
#Html.LabelFor(m => m.Username, new { #class = "entryFieldLabel" })
</div>
</div>
<div>
<div>
<button name="button" value="save" class="formbutton" id="saveButton">save</button>
<button name="button" value="cancel" class="formbutton" id="cancelButton">cancel</button>
</div>
}
</div>
<div id="NonEditable">
<div>
<div>
#Html.LabelFor(m => m.Username, new { #class = "entryFieldLabel" })
</div>
</div>
<div>
<div>
<button name="button" value="edit" class="formbutton" id="editButton" type="button">edit</button>
</div>
</div>
</div>
and the c# methods:
public ActionResult EditUser(AzaraUserModel AzaraUserModel, string button)
{
if (button == Tumormodelle.Properties.Resources.Save)
{
if (ModelState.IsValid)
{
azaraUserManagement.Update(AzaraUserModel.Username, AzaraUserModel.Title, AzaraUserModel.FirstName, AzaraUserModel.LastName, AzaraUserModel.EMailAddress, null, AzaraUserModel.Phone, AzaraUserModel.UserID, (byte)AzaraUserModel.ShowMail.ID);
ViewBag.Message = Tumormodelle.Properties.Resources.Personal_Data_Changed;
ViewBag.Editable = true;
}
else ViewBag.Editable = false;
BindShowMailList();
return PartialView("AccountInformation", AzaraUserModel);
}
else
{
return RedirectToAction("OpenAccountInformation", "ManageUsers");
}
}
public ActionResult UserInformation()
{
return View("UserInformation");
}
public PartialViewResult OpenAccountInformation()
{
AzaraUserModel AzaraUserModel = new AzaraUserModel(azaraUserManagement.GetSingle(AzaraSession.Current.UserComparison.GetUser().Id));
BindShowMailList();
ViewBag.Editable = true;
return PartialView("AccountInformation", AzaraUserModel);
}
Edit: With help of Chrome debugger i find out, that the error is thrown in the moment form becomes submited.
Ajax.BeginForm will be generating inline script in the generated HTML of your page, which you have disallowed by use of script-src 'self' in your Content Security Policy.
If you want to use the CSP to prevent any inline injected scripts you must use Html.BeginForm instead and add the JavaScript to submit this via Ajax in an external .js file.
try to add this attribute to your controller post action
[ValidateInput(false)]

Data Annotation doesn't not work if control generates from List View Model

I have below view model
public class QuestionarrieAnswersViewModel
{
public long QuestionID { get; set; }
public string Question { get; set; }
[Required(ErrorMessage="required")]
[StringLength(255, ErrorMessage = "Maximum 255 characters are allowed.")]
public string Answer { get; set; }
}
and i am generating view in below way
#model List<BusinessLayer.Models.ViewModel.QuestionarrieAnswersViewModel>
#using (Ajax.BeginForm("SaveQuestionarrie", "Member", FormMethod.Post, new AjaxOptions { OnBegin = "OnBegin", OnComplete = "OnComplete" }, new { #class = "form-horizontal" }))
{
for(int i=0;i<Model.Count;i++)
{
<div class="control-group">
<div class="head_form">
<label class="control-label">#Model[i].Question</label>
<div class="controls">
#Html.TextAreaFor(m=>m[i].Answer)
#Html.ValidationMessageFor(m => m[i].Answer)
#Html.HiddenFor(m=>m[i].QuestionID)
</div>
</div>
</div>
}
<div class="control-group">
<div class="controls">
<button class="btn" type="submit">Save</button>
</div>
</div>
}
I have set dataannotation on Answer field in above model but its not applying in above view while it works if i generate view in below way
#model BusinessLayer.Models.ViewModel.QuestionarrieAnswersViewModel
#using (Ajax.BeginForm("SaveQuestionarrie", "Member", FormMethod.Post, new AjaxOptions { OnBegin = "OnBegin", OnComplete = "OnComplete" }, new { #class = "form-horizontal" }))
{
#Html.TextAreaFor(m => m.Answer)
#Html.TextAreaFor(m => m.QuestionID)
<div class="control-group">
<div class="controls">
<button class="btn" type="submit">Save</button>
</div>
</div>
}
What's going wrong here...
In order to fire those validation rules, you'll need to use an EditorFor instead of a TextAreaFor.
It's because there's an outstanding issue with validation of TextArea's, see here: http://aspnet.codeplex.com/workitem/8576.
This is due to a bug in the version of jquery.validate.unobtrusive.js that was released with ASP.NET MVC3. This answer is on the same bug, the solution to this is to upgrade to the latest version of jquery.validate.unobtrusive.js - either grab it from an MVC4 project or update using NuGet.
The jquery.validate.unobtrusive.js script doesn't seem to have a version number so if you search in the script for a function called escapeAttributeValue, then this is a version of the script that has this bug fix.
The problem that is addressed in the bug fix is how to handle markup generated having name attributes containing characters that need escaping in a jQuery selector. In this case
<textarea cols="20" name="[0].Answer" rows="2"></textarea>
needs this selector
$('[name=\\[0\\]\\.Answer]')
The client-side DataAnnotation (validation) does not work for the Html.TextAreaFor() helper.
To make it work, you have to decorate the 'Answer' property with the [DataType(DataType.MultilineText)] attribute. And in the view, use Html.EditorFor() helper instead of the Html.TextAreaFor() helper mehthod.
See similar SO answer asp.net mvc TextAreaFor is not getting validated as a required field.

Categories