Showing text for checkboxfor in razorview - razor

USING ASP .Net MVC 4 , Razor View
I have a CheckBoxFor:
<div class="editor-checkbox-field">
#Html.CheckBoxFor(model => model.Is2ndMailBody, new { #name = "secMailBody", #id = "secMailBody", #class = "secMailBody", #onclick = "disable(this.form.secMailBody)", #value = "Create Table", #text = "Create Table" })
</div>
But the CheckBox itself is showing. How can i show a text what the CheckBox for?
my model has :
public bool IsChecked { get; set; }
javascript is working fine and css also. I just want to know how i can show a text for this checkbox?
EDIT 1 :
I want the text Create Second Mail Body in the right side of the check box.

Answer 1: Just put the string right after the CheckBox like below.
<div class="checkbox">
<label>
#Html.CheckBoxFor(m => m.Is2ndMailBody) Create Second Mail Body
</label>
</div>
Answer 2: In Model,
[Display(Name = "Create Second Mail Body")]
public bool Is2ndMailBody{ get; set; }
In View
<div>
#Html.CheckBoxFor(m => m.IsChecked)
#Html.LabelFor(m => m.Is2ndMailBody)
</div>

First add filter to your model that called DisplayAttribute
[Display(Name = "Some Text")]
public bool IsChecked { get; set; }
And you can use Label for model
#Html.LabelFor(model => model.Is2ndMailBody)

You can use
#Html.DisplayNameFor
instead of
#Html.LabelFor
in Alizra's answer. This way, .label css style won't be applied to your text.

If you are using bootstrap you can do this
<div class="checkbox">
<label>
#Html.CheckBoxFor(m => m.Is2ndMailBody) Create Second Mail Body
#Html.ValidationMessageFor(m => m.Is2ndMailBody)
</label>
</div>
example from: http://getbootstrap.com/css/

In your model class use Data Annotations to give a display name to the property
You need to have this using statement on top of the model class
using System.ComponentModel.DataAnnotations;
Then set the Display Name attribute
[Display(Name = "Create second mail body")]
public bool IsChecked { get; set; }
After that in your view use wrap the checkbox with the following div tag. You will need to have bootstrap CSS referenced in the view if it's not
<div class="checkbox">
#Html.CheckBoxFor(m => m.Is2ndMailBody, new { htmlAttributes = new { #class = "form-control" } })
#Html.LabelFor(m => m.Is2ndMailBody, new { #class = "control-label" })
</div>
Hope this will help

You can try this:
<div class="editor-checkbox-field">
<label> Create Second Mail Body #Html.CheckBoxFor(model => model.Is2ndMailBody, new { #name = "secMailBody", #id = "secMailBody", #class = "secMailBody", #onclick = "disable(this.form.secMailBody)", #value = "Create Table", #text = "Create Table" }) </label>
</div>
That is:
<label> Your text #HTML.checkBoxFor() </label>

Related

Asp.net mvc - how to show rich text without the html tags?

I DO NOT want to show the html tags in the content to the User. How to I do that?
I have a maintenance app that adds/edits blog content. It has a rich text editor.
When the content is saved in the SQL server database in a column defined as varchar(max), it saves it with html tags.
The edit feature retrieves it from the database and shows that:
Database:
Now when I want to display the content to the User in a view (.cshtml), I DO NOT want to see the html tags.
Here is the view (not showing all of the code):
#model GbngWebClient.Models.BlogPublishedByBlogIdVM
<h2 class="page-header"><span class="blogtitle">#Session["BlogTitle"]</span></h2>
#{
Layout = "~/Views/Shared/_LayoutUser.cshtml";
}
#if (ViewBag.errormessage != null)
{
<p class="alert alert-danger" id="errorMessage">#ViewBag.errormessage</p>
}
<br />
<div>
Return To Select a Blog
</div>
<br />
#if (Model != null)
{
<div class="panel panel-default toppanel">
<div class="panel-body">
<div class="row">
<div class="col-md-2">
#Html.LabelFor(model => model.BlogPublishedByBlogId.CreatedDateTime)
#Html.TextBoxFor(model => model.BlogPublishedByBlogId.CreatedDateTime, new { #class = "form-control", #disabled = "disabled" })
</div>
<div class="col-md-2">
#Html.LabelFor(model => model.BlogPublishedByBlogId.ModifiedDateTime)
#Html.TextBoxFor(model => model.BlogPublishedByBlogId.ModifiedDateTime, new { #class = "form-control", #disabled = "disabled" })
</div>
</div>
<br />
<div class="row">
<div>
#Html.DisplayFor(model => model.BlogPublishedByBlogId.BlogContent, new { #class = "form-control blogContent", #disabled = "disabled" })
</div>
</div>
<br />
}
Here are the models (not showing all of the properties):
namespace GbngWebClient.Models
{
public class BlogPublishedByBlogIdVM
{
public BlogPublishedByBlogIdVM()
{
this.BlogPublishedByBlogId = new BlogPublishedByBlogId();
}
public BlogPublishedByBlogId BlogPublishedByBlogId { get; set; }
}
}
using System;
using System.ComponentModel.DataAnnotations;
namespace GbngWebClient.Models
{
public class BlogPublishedByBlogId
{
[Required]
[Display(Name = "Content")]
public string BlogContent { get; set; }
}
}
Use
#Html.Raw(Model.BlogContent)
Html Helper Raw will be use for your case.
#html.Raw("").

data passed from view does not remain after post back

I am unable to find a solution for this as I think this is a bug, or maybe I am not seeing something I should have.
I am passing a model from controlled to view as strongly typed data. However, only one parameter is bugged, it clears it's data after post-back.
When I click Search..
You can see here, the date from Closed Time is still there, but the text from Cut Off time has gone. The date you see at the end is the value of #Model.CutOffTimeFrom - #Model.CutOffTimeTo just to see if the data was cleared or deleted, but it's not, it's just the display on the EditorFor was removed.
I also tried this one, using <input> tag but it's still the same output.
Below is my model:
[AssertThat("CutOffTimeFrom <= CutOffTimeTo", ErrorMessage = "Date To should be greater than Date From")]
[RequiredIf("CutOffTimeFrom != null", ErrorMessage = "Date From is required")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? CutOffTimeFrom { get; set; }
[RequiredIf("CutOffTimeTo != null", ErrorMessage = "Cut Off Time From is required")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? CutOffTimeTo { get; set; }
and here is the view:
<div>
#*<input type="date" name="CutOffTimeFrom" value="#Model.CutOffTimeFrom" class="form-control input-sm" />-<input type="date" name="CutOffTimeTo" value="#Model.CutOffTimeTo" class="form-control input-sm" />*#
#Html.EditorFor(m => m.CutOffTimeFrom, new { htmlAttributes = new { #class = "form-control input-sm" } }) - #Html.EditorFor(m => m.CutOffTimeTo, new { htmlAttributes = new { #class = "form-control input-sm" } })
#Html.ValidationMessageFor(model => model.CutOffTimeFrom, "", new { #class = "text-danger" })
#Html.ValidationMessageFor(model => model.CutOffTimeTo, "", new { #class = "text-danger" })
</div>
All other fields works just fine. Only Cut Off time is being cleared, although it satisfies the search criteria, value is still passed on the model, but it's just not displayed on the view.
Anyone encountered this issue?
Can we see the Controller handling this, because it might happen that its not model binding
I thoroughly checked the differences of each element, property, parameter and saw one difference, the date format. Saw the bug upon checking inspect element of each EditorFor and saw they were different dates, 2019/02/08 and 02/08/2019, where the latter is wrong.
Changed it from:
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
To:
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
Probably the [DataType(DataType.Date)] is unable to render 02/08/2019 that's why it doesn't repopulate the form.

Use Resources in a razor labelfor element

I have an ASP.NET MVC 5 project. I added internationalization and resources files, and now want to use some of those resources in the labels for the login for and registration form.
My question is how do I do this? If I just remove the razor code and put in the resource code, the layout is off.
Here is a code fragment:
<div class="form-group">
#Html.LabelFor(m => m.ConfirmPassword, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.ConfirmPassword, new { #class = "form-control" })
</div>
</div>
Now I want to change the #Html.LabelFor(m => m.ConfirmPassword, new { #class = "col-md-2 control-label" })part with #Resources.Resources.RegisterIntro while keeping the layout as it is.
Is this possible?
There are two ways 1"direct annotations" 2"Annotatinos with a resource"
Direct annotations
[Display(Name = "My Field")]
public string MyField { get; set; }
Annotatinos with a resource
[Display(Name = "My_Field",ResourceType = typeof(Resource))]
public string MyField { get; set; }
Second way will require to add a value in resource file Resource.resx.
Use which suits your purpose.

MvcHtmlString with Razor statements included

I find myself repeating this code block too often...
<div class="form-group">
<div class="col-sm-3 control-label">
#Html.LabelFor(m => m.Name)
</div>
<div class="col-sm-9">
#Html.TextBoxFor(m => m.Name, null, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Name)
</div>
</div>
I have been attempting to create a MvcHtmlString custom extension, but it assumes that the #Html.LabelFor commands are text and that is what is displayed.
EDIT: Thanks Joe and Stephen!! That's what I was missing.
Here's the final answer for my code block
static MvcHtmlString BaseFieldFor<TModel>(this HtmlHelper<TModel> helper, Expression<Func<TModel, string>> expression, MvcHtmlString innerHtml, string style = null) {
var labelDiv = new TagBuilder("div");
labelDiv.AddCssClass("col-sm-3 control-label");
labelDiv.InnerHtml += helper.LabelFor(expression, new {
htmlAttributes = new { #class = "form-control" }
});
var textDiv = new TagBuilder("div");
textDiv.AddCssClass("col-md-9");
textDiv.InnerHtml += innerHtml;
textDiv.InnerHtml += helper.ValidationMessageFor(expression);
var groupDiv = new TagBuilder("div");
groupDiv.AddCssClass("form-group");
groupDiv.InnerHtml += labelDiv;
groupDiv.InnerHtml += textDiv;
return new MvcHtmlString(groupDiv.ToString(TagRenderMode.Normal));
}
and for usage
public static MvcHtmlString FieldFor<TModel>(this HtmlHelper<TModel> helper, Expression<Func<TModel, string>> expression, string style = null) {
var innerHtml = helper.TextBoxFor(expression, null, new { #class = "form-control", style });
return BaseFieldFor(helper, expression, innerHtml, style);
}
public static MvcHtmlString DropDownListFor<TModel>(this HtmlHelper<TModel> helper, Expression<Func<TModel, string>> expression, IEnumerable<SelectListItem> list, string style = null){
var innerHtml = helper.DropDownListFor(expression, new SelectList(list, "Value", "Text"), new { #class = "form-control", style });
return BaseFieldFor(helper, expression, innerHtml, style);
}
And now I can use it simply!
<div class="panel-body form-horizontal">
#Html.FieldFor(m => m.Name)
#Html.FieldFor(m => m.Address1)
#Html.FieldFor(m => m.Address2)
#Html.FieldFor(m => m.City)
#Html.DropDownListFor(m => m.State, AllowableValues.StateList, "max-width: 200px;")
#Html.FieldFor(m => m.PostalCode, "max-width: 150px;")
#Html.FieldFor(m => m.Phone, "max-width: 150px;")
</div>
Your helper needs to use the inbuilt helper methods for generating your html. For example
MvcHtmlString label = LabelExtensions.LabelFor(helper, expression});
Refer this example for creating a helper that outputs similar html including the label, textbox and validation message.
You're not able to invoke the HTML helpers in the manner that you're trying to do so. All it will do is treat it as text out output the result as you've already seen.
Instead you need to reference the HTML helper along the lines of this:
string yourString = "Your string " + helper.LabelFor("text", "actionName");

Input type = "file" loses file automatically?

I have two inputs of type file, one in a partial view, and another in main page
In partial view
<input type="file" name="image" id="image" onchange="readURL(this)"/>
In main page
<input type="file" name="userProfilePic" id="userProfilePic" style="display:none" />
What I want is that when a user changes image/file on the visible file upload, the image/file should be updated on main/other input too. Here's my code.
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imagePreview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
// window['profilePic'] = input.files[0];
$('#userProfilePic').get(0).files[0] = input.files[0];
return false;
}
The Error
The error is quite weird, when I open my console, and check for files, it shows up sometime, and a moment later it don't.
In my console window
$('#userProfilePic').get(0).files[0]
File (file object details)
....
(after a second)
$('#userProfilePic').get(0).files[0]
undefined
And it isn't happening the first time only. Say sometimes, it shows the values for 5-6 times, then 7th time it won't...
$('#userProfilePic').get(0).files[0]
File (file object details)
....
(after a second)
$('#userProfilePic').get(0).files[0]
File (file object details)
....
(after a second)
$('#userProfilePic').get(0).files[0]
File (file object details)
....
(after a second)
$('#userProfilePic').get(0).files[0]
undefined
That's all the code I have, there is no other code. Now, as you can see in the code, I also set window[profilePic] to the file object. But if I check that in console window, it always shows no matter what? How is this happening?
The problem
I need to submit the form, but when I do, the image (the input file) is being sent as null, but sometimes as a valid file. As I explained earlier, when I check the value in console, it shows for first time, or some random number of times, then all of a sudden it is gone, while the variable that I set on window (window[profilePic]) always have that file object.
In case someone is wondering, the original/visible file input where user actually selects the file always has the value.
You cant do this for security reasons , all files uploaded via input type="file" have to be done manually by the user.
However as long as the user will upload an image anyway , you should do all the process you want in your server side script.
for further info , please refer to this post here :
How to set a value to a file input in HTML?
Why you try to use two inputfile for the same file?
if you try to make a form in a PartialView with a inputfile and extra data? I answered a very similar question here:
File upload in MVC when used in bootstrap modal returns null
1) make a model for used in the form with all elements for the form,
2) declare the model in the first line in the partial view
3) pass as parameter the model to the post function.
4) you use a Partial view, well is possible use this view in differents pages, you need specify the control to treatement the form.
An Example in code:
Model:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class PartialFormModel
{
[Required]
[StringLength(200)]
public string FileName { get; set; }
[StringLength(200)]
public string Title { get; set; }
[StringLength(1000)]
public string Description { get; set; }
public int? Order { get; set; }
[NotMapped]
public HttpPostedFileBase ImageFile { get; set; }
}
PartialVIEW:
#model YOURSPACENAME.Models.PartialFormModel
#using (Html.BeginForm("YourActionName", "YourControllerName", FormMethod.Post, new { #class = "form-horizontal", #role = "form", #enctype="multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-group">
#Html.LabelFor(model => model.FileName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FileName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FileName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ImageFile, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.ImageFile, new { #class = "form-control", type = "file" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
}
CONTROLLER
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult YourActionName(PartialFormModel obj)
{
if (ModelState.IsValid)
{
//your options
}
return PartialView("_EditSlider");
}
Considering that:
For security reasons you can't set value of input type="file"
programmatically.
Changing the type of an <input> throws a security error in some
browsers (old IE and Firefox versions).
I don't know actually what you want. But I exhort you to create a new input element, set its type to the one you want, say file, and set its properties according to your need. like this:
<script>
function createInputType(_type, _value, _name, _id, _class) {
var newObject = document.createElement('input');
newObject.type = _type;
newObject.value = _value;
newObject.name = _name;
newObject.id = _id;
newObject.className = _class;
return newObject;
}
</script>