Razor encodes everything - asp.net-mvc

Razor is encoding every unicode character. How to prevent that?
Example:
This is my Razor:
#Html.DropDownListFor(model => model.Category,
(IEnumerable<SelectListItem>) ViewBag.CategoriesList,
"موضوع صفحه را انتخاب کنید...", new{
#class = "form-control some-css"
})
And this the rendered html:
<select class="form-control some-css" id="Category" name="Category">
<option value="">
موضوع صفحه را انتخاب کنید...
</option>
<option value="SomeValue">
موزه
</option>
<!-- some other options -->
</select>

You could use Html.Raw()
#Html.DropDownListFor(model => model.Category,
(IEnumerable<SelectListItem>)ViewBag.CategoriesList,
Html.Raw("موضوع صفحه را انتخاب کنید..."), new
{
#class = "form-control some-css"
})

Related

my tag helper Drop Down Select Will Not render properly in .NET core

<div class="form-group">
<label asp-for="roles" class="control-label"></label>
<select asp-for="roles" class="custom-select" asp-items="#(new Select List(ViewBag.Roles))">
<option value="">Assign Role</option>
</select>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">State</label>
<div class="col-sm-10">
<select asp-for="roles" class="form-control custom-select" style="height:20px" asp-items="#(new Select List(ViewBag.Roles,"Id","Name"))">
<option value="">Large select</option>
</select>
</div>
</div>
my drop down in not responsive any help
how to make drop down responsive
It is possible that the value of ViewBag.Roles is assigned incorrectly. Here is an example.
In Index.cshtml
#{
ViewBag.Roles = new List<MyModel>
{
new MyModel{Id=1, Name="thisname"},
new MyModel{Id=2, Name="thisname2"},
};
}
<div class="form-group row">
<label class="col-sm-2 col-form-label">State</label>
<div class="col-sm-10">
<select asp-for="roles" class="form-control custom-select" style="height:20px"
asp-items="#(new SelectList(ViewBag.Roles,"Id","Name"))">
<option value="">Large select</option>
</select>
</div>
Here is the model.
public class MyModel
{
public int Id { get; set; }
public string Name { get; set; }
}
Result.

How to return select option value?

This is my Html
<div class="form-row">
<div class="col-md-3">
<div class="position-relative form-group">
<label class="">Status</label>
<select class="form-control" id="txtStatus" name="Status">
<option value="A">Active</option>
<option value="I">Inactive</option>
</select>
</div>
</div>
</div>
how to do something like this is asp.net mvc?
<option value="A" <%if Status="A" then%>Selected
<%end if%>>Active</option>
<option value="I" <%if Status="I" then%>Selected
<%end if%>>Inactive</option>
#Model.Status is my value.
How to Do like this :
<option value="A" <%if #Model.Status="A" then%>Selected
<%end if%>>Active</option>
The proper way to do is to use the #Html.DropDownListFor helper method. In the Model we need to introduce a property for available statuses that can be selected.
public class ViewModel
{
public string Status { get;set;}
public IEnumerable<SelectListItem> Statuses { get;set;}
public ViewModel()
{
Statuses= new List<SelectListItem>
{
new SelectListItem {Text = "-- Select Status --", Value = ""},
new SelectListItem {Text = "Active", Value = "A"},
new SelectListItem {Text = "InActive", Value = "I"}
};
}
}
and in view then we can write :
#Html.DropDownListFor(x => x.Status, Model.Statuses,
new { #class ="form-control" , id ="txtStatus"})
It will generate html something similar to :
<select class="form-control" id="txtStatus" name="Status">
<option value="A">Active</option>
<option value="I">Inactive</option>
</select>
UPDATE:
You can do with plain html like:
<option value="A" #(Model.Status =="A" ? "selected" : "")>Active</option>
<option value="I" #(Model.Status =="I" ? "selected" : "")>Inactive</option>

Both Date & Time EditorFor editor in mvc razor?

When using #Html.EditorFor thing for date or time in mvc razor one can define a model like
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:hh:mm tt}")]
[DataType(DataType.Time)]
or
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
however, when I change the syntax to DataType.DateTime, in my view I don't get datepicker or time mask with spinner, it just gives me a blank textbox. In my view I need something like dd/mm/yyyy hh:mm posting to the database. Is there a way to do it in mvc razor without using bootstrap datetimepicker/jquery-ui? I am using MVC5.
Answer for 2022.
Try using the default elements from HTML5. Add #type = "date" and #type = "date" to the htmlAttributes
<div class="row">
<div class="col-12 col-md-6">
#Html.LabelFor(Model => Model.TheDate)
#Html.EditorFor(Model => Model.TheDate, new { htmlAttributes = new { Name = "TheDate", #class = "form-control", #type = "date" } })
#Html.HiddenFor(Model => Model.TheDate)
</div>
<div class="col-12 col-md-6">
#Html.LabelFor(Model => Model.TheTime)
#Html.EditorFor(Model => Model.TheTime, new { htmlAttributes = new { Name = "TheTime", #class = "form-control", #type = "time" } })
#Html.ValidationMessageFor(Model => Model.TheTime, "", new { #class = "text-danger" })
</div>
</div>
What you´re doing here is adding the correct types (type="date", and type="time") to the HTML elements. This is the rendered result:
<div class="row">
<div class="col-12 col-md-6">
<label for="TheDate">Date</label>
<input Name="TheDate" class="form-control text-box single-line" data-val="true" data-val-required="Enter the correct date." id="TheDate" name="TheDate" type="date" value="2022-08-18" />
<span class="field-validation-valid text-danger" data-valmsg-for="TheDate" data-valmsg-replace="true"></span>
</div>
<div class="col-12 col-md-6">
<label for="TheTime">Time</label>
<input Name="TheTime" class="form-control text-box single-line" data-val="true" data-val-required="Enter the correct time." id="TheTime" name="TheTime" type="time" value="10:00" />
<span class="field-validation-valid text-danger" data-valmsg-for="TheTime" data-valmsg-replace="true"></span>
</div>
</div>
What you get in the interface (using Google Chrome v104):
and

ASP.NET MVC: The required anti-forgery form field “__RequestVerificationToken” is not present

The following error occurs when building my code
The required anti-forgery form field “__RequestVerificationToken” is not present
This is the controller method:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel1 model)
{
if (ModelState.IsValid)
{
int month = DateTime.ParseExact(model.BirthMonth.ToString(), "MMMM", CultureInfo.CurrentCulture).Month;
DateTime birthDate = new DateTime(model.BirthYear, month, model.BirthDay);
var user = new ApplicationUser { Email = model.Email, UserName = model.UserName, Name = model.Name, Surname = model.Surname, BirthDate = birthDate, Country = model.Country, PhoneNumber = model.PhoneNumber };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
db.Users.Add(user);
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking here");
var users = db.Users.ToList();
var adminUsers = db.Users.Where(u => u.IsAdmin == true).ToList();
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
//VIEW
#model GAPT.Models.RegisterViewModel1
#{
ViewBag.Title = "Tours-Maltin";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div id="content">
<div class="container">
<div class="row">
<div class="col-md-6">
#Html.AntiForgeryToken()
<form action="#Url.Action("Register","Account")" method="post">
#*"Index","Home"*#
<div class="form-group" style="width:280px">
#*<label for="name-login">Surname <p style="color:red; display:inline"> *</p></label>
<input type="text" class="form-control" id="name-login" required>*#
#Html.LabelFor(m => m.Name, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Name, new { #class = "form-control" })
</div>
</div>
<div class="form-group" style="width:280px">
#*<label for="surname-login">Surname <p style="color:red; display:inline"> *</p></label>
<input type="text" class="form-control" id="surname-register" required>*#
#Html.LabelFor(m => m.Surname, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Surname, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#*<label for="email-login">Email <p style="color:red; display:inline"> *</p></label>
<input type="email" class="form-control" id="email-login" required>*#
#Html.LabelFor(m => m.Email, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Email, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<script>
</script>
<label for="dob-login" style="display:block;">Date of Birth <p style="color:red; display:inline"> *</p></label>
<select name="BirthDay" id="BirthDay" onchange="runDay()" style="width:91px;height:34px;font-size:14px; text-align:center" required>
<option value=""> - Day - </option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
</select>
<select name="BirthMonth" id="BirthMonth" onchange="runMonth()" style="width:91px;height:34px;font-size:14px;text-align:center" required>
<option value=""> - Month - </option>
<option value="January">January</option>
<option value="Febuary">Febuary</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
</select>
<select name="BirthYear" id="BirthYear" onchange="runYear()" style="width:91px; height:34px;font-size:14px; text-align:center" required>
<option value=""> - Year - </option>
<option value="2000">2000</option>
<option value="1999">1999</option>
<option value="1998">1998</option>
<option value="1997">1997</option>
<option value="1996">1996</option>
<option value="1995">1995</option>
<option value="1994">1994</option>
<option value="1993">1993</option>
<option value="1992">1992</option>
<option value="1991">1991</option>
<option value="1990">1990</option>
<option value="1989">1989</option>
<option value="1988">1988</option>
<option value="1987">1987</option>
<option value="1986">1986</option>
<option value="1985">1985</option>
<option value="1984">1984</option>
<option value="1983">1983</option>
</select>
<script>
function runDay() {
//if (document.getElementById("srt").value != "") {
var day = document.getElementById("Day").value;
document.getElementById("BirthDay").value = day;
//}
}
</script>
<script>
function runMonth() {
//if (document.getElementById("srt").value != "") {
var month = document.getElementById("BirthMonth").value;
document.getElementById("BirthMonth").value = month;
//}
}
</script>
#*#Html.DropDownListFor(m => m., month: month, htmlAttributes: new { #class = "BirthMonth" })*#
<script>
function runYear() {
//if (document.getElementById("srt").value != "") {
var year = document.getElementById("Year").value;
document.getElementById("BirthYear").value = year;
//}
}
</script>
</div>
<div class="form-group">
#*<label for="select-country" style="display:block;">Country <p style="color:red; display:inline"> *</p></label>
<input type="text" id="country" class="form-control" style="padding-right:25%;text-align:center;padding-left:25%;">*#
#Html.LabelFor(m => m.Country, new { #class = "col-md-2 control-label", #id="country"})
<div class="col-md-10">
#Html.TextBoxFor(m => m.Country, new { #class = "form-control" })
</div>
<!--problem-->
<!--<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>-->
<script src="~/Scripts/countrySelect.min.js"></script>
<script>
$("#country").countrySelect();
</script>
</div>
<div class="form-group">
#*<label for="username-login">Username<p style="color:red; display:inline"> *</p></label>
<input type="text" pattern='^(?=.{6,20}$)(?!.*[._-]{2})[a-z][a-z0-9._-]*[a-z0-9]$' title="Username needs to be between 6 to 20 characters and can only contain alphanumeric characters, _ . or - which cannot be used near each other" class="form-control" id="username-login" required>*#
#Html.LabelFor(m => m.UserName, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.UserName, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#*<label for="mobile-login" style="text-wrap:normal">Mobile Number - So we can send you important information and reminders about your tours <p style="color:red; display:inline"> *</p></label>
<input type="tel" class="form-control" id="phone" style="padding-right: 26.7%;" required>*#
#Html.LabelFor(m => m.PhoneNumber, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.PhoneNumber, new { #class = "form-control", id = "mobile" })
</div>
</div>
<div class="form-group">
#*<label for="password-login">Password <p style="color:red; display:inline"> *</p></label>
<input type="password" pattern='^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!#"$%()^&*_=+-]).{8,16}$' title='Password needs to be between 8 to 20 characters and must include alphanumeric characters. Special characters accepted _ - . which must not be near each other.' class="form-control" id="password-login" required>*#
#Html.LabelFor(m => m.Password, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.Password, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#*<label for="confirm-password-login">Confirm Password <p style="color:red; display:inline"> *</p></label>
<input type="password" class="form-control" id="confirm-password-login" required>*#
#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>
<div class="text-center">
<button type="submit" class="btn btn-template-main"><i class="fa fa-user-md"></i> Register</button>
</div>
</form>
</div>
</div>
<div class="col-md-6 hidden-sm hidden-xs">
<div class="box" style="padding-left:14px; padding-right:14px;">
<h2 class="text-uppercase">Login</h2>
<p class="lead">Already our customer?</p>
<hr>
<form action="#Url.Action("Login","Account")" method="post">
<div class="form-group">
<label for="text">Username or Email<p style="color:red; display:inline"> *</p></label>
<input type="text" class="form-control" id="email" required>
</div>
<div class="form-group">
<label for="password">Password <p style="color:red; display:inline"> *</p></label>
<input type="password" class="form-control" id="password" required>
<br>
Forgot your Password?</label>
</div>
<div class="text-center" style="padding-top: 7px;">
<button type="submit" class="btn btn-template-main"><i class="fa fa-sign-in"></i> Log in</button>
</div>
</form>
</div>
</div>
</div>
<!-- /.row -->
</div>
<!-- /.container -->
</div>
<!-- /#content -->
Followed other questions however, the problem still persists.
thanks
You have the to put the token inside the form:
<form action="#Url.Action("Register","Account")" method="post">
#Html.AntiForgeryToken()
You're placing it before the form element opens, so it's not being included in the form POST.

MVC File uploads collection is always null

This was working and now for reasons unknown my file collection is null
VIEW
#section termimalContent {
#using (Html.BeginForm("Add", "Terminals_Policies", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>
<h2>
Create new policy</h2>
</legend>
<p>
<strong>Assigning devices to Node:</strong> #Model.GroupName</p>
<div class="editor-label">
#Html.LabelFor(model => model.PolicyName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PolicyName)
#Html.ValidationMessageFor(model => model.PolicyName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PolicyType)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.SelectedItem, new SelectList(Model.PolicyType, "Value", "Text"),new {#class = "PackageDDL"})
#Html.ValidationMessageFor(model => model.SelectedItem)
</div>
#foreach (var pick in Model.PackageTypeItems)
{
<div class="editor-label">
<label for="#pick.Name">
#pick.Name:</label>
</div>
<div class="editor-field">
<input class="text-box single-line" type="file" name="#pick.Name.Trim()" id="#pick.Name.Trim()" data-val="#pick.IsRequired.ToString().ToLower()" data-val-required="Please select a file" />
#Html.ValidationMessage(pick.Name.Trim())
</div>
}
#Html.HiddenFor(model => model.GroupId)
#Html.HiddenFor(model => model.GroupName)
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
}
HTML Generated
<form action="/Terminals_Policies/Add/1" enctype="multipart/form-data" method="post"> <fieldset>
<legend>
<h2>
Create new policy</h2>
</legend>
<p>
<strong>Assigning devices to Node:</strong> Root</p>
<div class="editor-label">
<label for="PolicyName">PolicyName</label>
</div>
<div class="editor-field">
<input class="text-box single-line" data-val="true" data-val-length="Policy name cannot be longer than 50 characters." data-val-length-max="50" data-val-required="Please enter the policy name" id="PolicyName" name="PolicyName" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="PolicyName" data-valmsg-replace="true"></span>
</div>
<div class="editor-label">
<label for="PolicyType">PolicyType</label>
</div>
<div class="editor-field">
<select class="PackageDDL" data-val="true" data-val-number="The field SelectedItem must be a number." id="SelectedItem" name="SelectedItem"><option value="1">IT application</option>
<option value="3"> definition</option>
<option value="4">definition</option>
<option value="5">project</option>
<option value="6">relay schedules</option>
<option value="7">table data</option>
<option value="9">transfer definition</option>
<option value="10">firmware update request</option>
<option value="11"> firmware update request</option>
<option value="12">dat</option>
<option value="15"> firmware</option>
<option value="16"> hex</option>
<option value="17">project</option>
<option value="18">firmware</option>
</select>
<span class="field-validation-valid" data-valmsg-for="SelectedItem" data-valmsg-replace="true"></span>
</div>
<div class="editor-label">
<label for="IT application file ">
IT application file :</label>
</div>
<div class="editor-field">
<input class="text-box single-line" type="file" name="IT application file" id="IT application file" data-val="true" data-val-required="Please select a file" />
<span class="field-validation-valid" data-valmsg-for="IT application file" data-valmsg-replace="true"></span>
</div>
<input data-val="true" data-val-number="The field GroupId must be a number." data-val-required="The GroupId field is required." id="GroupId" name="GroupId" type="hidden" value="1" />
<input id="GroupName" name="GroupName" type="hidden" value="Root" />
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
</form>
Controller:
[HttpGet]
public ActionResult Add(int id)
{
_polAdd = CreatePolicyAddModel(id);
return View(_polAdd);
}
[HttpPost]
public ActionResult Add(IEnumerable<HttpPostedFileBase> files, vmPoliciesAdd model)
{
_policyLogic.AddPolicyFile(files,model.PolicyName,(int)model.SelectedItem, "FILE");
return View();
}
On the post action of controller the colelction is empty, can anyone see an obvious mistake
Naming issue:
<input class="text-box single-line" type="file" name="IT application file" id="IT application file" data-val="true" data-val-required="Please select a file" />
Should of course be:
<input class="text-box single-line" type="file" name="files" id="IT application file" data-val="true" data-val-required="Please select a file" />
So fix your Razor code and make sure you have applied correct name to your file input if you expect the model binder to be able to bind to an action argument called files:
<input class="text-box single-line" type="file" name="files" id="#pick.Name.Trim()" data-val="#pick.IsRequired.ToString().ToLower()" data-val-required="Please select a file" />
Ah an by the way id's cannot contain spaces. So you've got a broken HTML. The following seems wrong: id="#pick.Name.Trim()" as well.

Resources