How to bind input field to editfor model MVC - asp.net-mvc

I have the following javascript and input fields within my model.
script type="text/javascript">
function sum() {
var txtFirstNumberValue = document.getElementById('money1').value;
var txtSecondNumberValue = document.getElementById('money2').value;
var txtThirdNumberValue = document.getElementById('money3').value;
var result = parseFloat(txtFirstNumberValue) + parseFloat(txtSecondNumberValue) + parseFloat(txtThirdNumberValue);
if (!isNaN(result)) {
document.getElementById('Total').value = result;
}
}
</script>
<div class="form-group">
#Html.LabelFor(model => model.Total, "Total", new { #class = "control-label col-md-5" })
<div class="col-md-offset-0">
<input type="text" id="Total" name="Total" />
#*#Html.EditorFor(model => model.Total)*#
#Html.ValidationMessageFor(model => model.Total)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.money1, "money1", new { #class = "control-label col-md-5" })
<div class="col-md-offset-0">
#*#Html.EditorFor(model => model.money1)*#
<input type="text" id="money1" onkeyup="sum();" name="money1" />
#Html.ValidationMessageFor(model => model.money1)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.money2, "money2", new { #class = "control-label col-md-5" })
<div class="col-md-offset-0">
#*#Html.EditorFor(model => model.money2)*#
<input type="text" id="money2" onkeyup="sum();" name="money2" />
#Html.ValidationMessageFor(model => model.money2)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.money3, "money3", new { #class = "control-label col-md-5" })
<div class="col-md-offset-0">
#*#Html.EditorFor(model => model.money3)*#
<input type="text" id="money3" onkeyup="sum();" name="money3" />
#Html.ValidationMessageFor(model => model.money3)
</div>
</div>
This all works fine. When I type a value into the 3 money fields the resulting value appears in the Total field. Within MVC if I click on the details view it shows all four values, however if I click on the edit view all four fields are blank. Question is how do I get the values to appear and remain in edit mode?

Well, for starters your model-bound input fields are commented out:
#*#Html.EditorFor(model => model.money1)*#
In order to get those to work you'd need to un-comment them.
You could just manually populate your markup with the model values, something like this:
<input type="text" id="money1" onkeyup="sum();" name="money1" value="#model.money1" />
That should pre-populate that input with the model's money1 value. Though you're assuming the responsibility of manually implementing anything else that the built-in HTML helpers would provide for you. Unless there's a compelling reason not to use Html.EditorFor() I imagine that would be the better option.

Related

Using MVC HtmlHelpers, how to send a form with a value from database along with User-filled values?

I'm trying to write a Bank Application. In the Transaction Page, I want to take the value of CheckingAccountId from the User Accounts Database (User.Identity.GetUserId()). But, how should I assign the value of User.Identity.GetUserId() to CheckingAccountId. This is the relevant Razor View Page Code:
using (Html.BeginForm("Deposit", "Transaction", FormMethod.Post, new {
#class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken();
<h4>Deposit Section</h4>
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.Id, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Id, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.TransactionAmount, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.TransactionAmount, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.CheckingAccountId, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#{
var userName = User.Identity.GetUserName();
}
#*THIS IS THE BEST I COULD DO. I NEED HELP HERE*#
#*#m.CheckingAccountId = userName*#
#Html.DisplayName(userName)**
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Deposit" />
</div>
</div>
UPDATE:
I just found out that we can achieve this by adding the same in the ConnectionString when writing the SQL Query for pushing the transaction into the database. The solution would look something like this:
INSERT INTO table ( checkingaccountid, model_data ) VALUES ( $id, $data );
But I would still like to know if it's possible to send this id from the form when submitted along with the other data.

ASP.NET MVC - A potentially dangerous Request.Form value was detected from the client

Am trying to click save button to update what I have in text editor using ckeditor but I got this error
A potentially dangerous Request.Form value was detected from the client (OPTION_VALUE="Welcome to the Na...").
The controller is shown below
Controller
public ActionResult EditRegistrationGuideline(long id)
{
OPTIONS options = _optionsService.GetOption(id);
return View(options);
}
//
// POST: /Product/Edit/5
[HttpPost]
public ActionResult EditRegistrationGuideline(long id, OPTIONS options)
{
try
{
// TODO: Add update logic here
if (ModelState.IsValid)
{
options.OPTION_ID = id;
options.ACTION_STATUS = 0;
options.CREATED_DATE = DateTime.Now;
_optionsService.AddOption(options);
return RedirectToAction("Index");
}
}
catch
{
//return View();
ModelState.AddModelError("", "We cannot edit this Option. Verify your data entries !");
}
return View();
}
and the view is here
View
#{
//ViewBag.Title = "CreateRegistrationGuideline";
}
<div class="content-header clearfix">
<h1 class="pull-left">
<i class="fa fa-plus"> </i> Edit Registration Guideline
</h1>
<div class="col-xs-3 pull-right">
<input type="button" class="btn btn-block btn-warning" value="Back" onclick="location.href='#Url.Action("IndexRegistrationGuideline", "Options")'" />
</div>
<div class=" box box-body box-primary">
#using (Html.BeginForm("EditRegistrationGuideline", "Options", FormMethod.Post, new { #class = "form-horizontal", #enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#*<h4>OPTIONS</h4>
<hr />*#
#*#Html.ValidationSummary(true)*#
#Html.ValidationSummary(false, null, new { #class = "text-danger" })
<div class="row .col">
<div style="margin-top:20px" class="mainbox col-md-12 col-md-offset-0 col-sm-8 col-sm-offset-2">
<div class="panel panel-info">
<div class="panel-heading">
<div class="panel-title">Edit Option</div>
</div>
<div class="panel-body">
#*<div class="form-group">
#Html.LabelFor(model => model.OPTION_NAME, new { #class = "control-label col-md-2" })
<div class="col-md-10">*#
#*#Html.LabelFor(model => model.OPTION_NAME, new { #class = "control-label col-md-2" })
<div class="col-md-10">*#
#*#Html.EditorFor(model => model.OPTION_NAME)*#
#*#Html.HiddenFor(model => model.faculty_activation_date, new { #Value = System.DateTime.Now })*#
#Html.HiddenFor(model => model.OPTION_NAME)
#Html.ValidationMessageFor(model => model.OPTION_NAME)
<div class="form-group">
#*#Html.LabelFor(model => model.OPTION_VALUE, new { #class = "control-label col-md-2" })*#
<div class="col-md-10">
#Html.LabelFor(model => model.OPTION_VALUE, "Option Value")
#*<textarea class="form-control" placeholder="Enter Option Value" name="OPTION_VALUE" id="editor1"></textarea>*#
#Html.TextAreaFor(model => model.OPTION_VALUE, new { #class = "form-control", #id = "editor1" })
#Html.ValidationMessageFor(model => model.OPTION_VALUE, "", new { #class = "text-danger" })
</div>
</div>
#*<div>
#Html.LabelFor(model => model.OPTION_VALUE, "Option Value")
#Html.TextAreaFor(model => model.OPTION_VALUE, new { #type = "textarea", #id="editor1", #class = "form-control", #placeholder = "Enter Option Value", #autocomplete = "on" })
#Html.ValidationMessageFor(model => model.OPTION_VALUE, null, new { #class = "text-danger" })
</div>*#
#*<div class="form-group">
#Html.LabelFor(model => model.ACTION_STATUS, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ACTION_STATUS)
#Html.ValidationMessageFor(model => model.ACTION_STATUS)
</div>
</div>*#
</div>
<div class="panel-footer">
<div class="panel-title">
<div class="form-actions no-color">
<input type="submit" value="Save" class="btn btn-success" />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
}
#*<div>
#Html.ActionLink("Back to List", "Index")
</div>*#
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/jquery-3.1.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="https://cdn.ckeditor.com/4.5.7/standard/ckeditor.js"></script>
<script>
$(function () {
CKEDITOR.replace('editor1');
});
</script>
}
Please what do I do.
I use CKEDITOR
XSS error ("A potentially dangerous Request.Form value was detected from the client(...)").
Solution:
[ValidateInput(false)]
Differnce b/w them
AllowHtml:
The AllowHtml attribute can be applied to a Model property and it will disable the validation by ASP.Net MVC only for that particular property
Advantages
The AllowHtml attribute is developed for Model class.
The Scope is limited to specific property of the Model class.
It is the safe and recommended solution.
ValidateInput
The ValidateInput attribute can be applied to a Controller’s Action method and it will disable the validation by ASP.Net MVC only for that particular Action method.
Advantages
The Scope is limited to specific Action method of the Controller class.
If you have multiple properties accepting HTML content, then this method will reduce redundancy.
When Model class is not used for designing Form elements then this attribute is needed.For complete details Link
Just place ValidateInput(false) attribute on controller's action.
[HttpPost]
[ValidateInput(false)]
public ActionResult EditRegistrationGuideline(long id, OPTIONS options)
The other option is to place [AllowHtml] attribute on Model Property, have a look on SO post to get difference between them
ValidateInput(false) vs AllowHtml
I was experiencing a similar issue with the following error message A potentially dangerous Request.Form value was detected from the client.
As an alternative to the previous answers, I found encoding the value passed back to the controller worked. CKEditor allows you to do this by setting the config config.htmlEncodeOutput = true;.
The documentation for this can be found at: https://docs-old.ckeditor.com/ckeditor_api/symbols/CKEDITOR.config.html#.htmlEncodeOutput
I got this error while testing XSS on my site.
This is a very good feature that the model gives us that prevents XSS, CSRF from penetrating your site.
Do not disable it as much as possible.

How do i pass the values from html.editorfor() to my controller

This is the code generated by the Visual Studio when i added a view for my Edit function
I want to pass the values inside the <input> generated by the #Html.EditorFor() from the view to my controller.
How can i access those values? Can i do it without manually declaring textboxes via <input class="form-control text-box single-line" id="Surname" name="Surname" type="text"> ?
#using (Html.BeginForm("Save","my",FormMethod.Post)){
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>User</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #Value=Model.Name, #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
UPDATE
found the answer, i simply needed to pass this code as an argument in my function inside the controller that would create an object User with properties inside Include
public string Submit ([Bind(Include = "Name")] User user){
}

object name is bind as prefix in input control

currently I am working in asp.net mvc view
I create form using below code.
#{
T4.Models.Order o = new T4.Models.Order();
}
#using (Html.BeginForm("Create", "Default5", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Order</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => o.CustomerID, new {#class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model=>o.CustomerID)
#Html.ValidationMessageFor(model => o.CustomerID)
</div>
</div>
</div>
}
this code render perfectly but problem is it render with prefix of object's name.
show below html code
<input class="text-box single-line" data-val="true" data-val-required="The CustomerID field is required." id="o_CustomerID" name="o.CustomerID" type="text" value="">
you can see this html input control has id="o_CustomerID".I want that it only render with id="CustomerID".
I does not know why it takes object name as prefix.
please help me.
Thank You.
No need to initialize object of T4.Models.Order class.
#{
T4.Models.Order o = new T4.Models.Order();
}
Replace above code to:
#model T4.Models.Order
Then simple use:
<div class="form-group">
#Html.LabelFor(model => model.CustomerID, new {#class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model=> model.CustomerID)
#Html.ValidationMessageFor(model => model.CustomerID)
</div>
</div>

How to set first checkbox checked in mvc

Here i want to set the first checkbox checked.I am not understanding how,since its in a viewbag.
<div class="form-group">
#Html.LabelFor(m => m.RBO_Location, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#foreach (var item in (SelectList)ViewBag.Branches)
{
<div>
<input type="checkbox" name="selectedBranches" value="#item.Value" class="checkbox-inline" />
#Html.Label(item.Text, new { #class = "control-label" })
</div>
}
</div>
</div>
How to set first checkbox checked in mvc
This can be done using Jquery at Document.Ready.
$("input[type=checkbox][name=selectedBranches]:first").attr('checked','checked');

Resources