Here's the view which I'm using to enter the multiline article
I wish that you can also told me how to save the text properties such as bold italic too because it makes me very confused.
#model WEBSITI.Models.article
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm( "Create", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
#Html.LabelFor(model => model.bodyofarticle, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.bodyofarticle, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.bodyofarticle, "", new { #class = "text-danger" })
</div>
<input type="file" id="file" name="file" />
</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>
</div>
}
When a form is submitted, the asp.met mvc framework will inspect the request body to see whether it has any potentially dangerous content as HTML markup(Think about script injection). If it detects any dangerous content,the Request Validation module will throw an error. This is by design
To explicitly allow the form posting with Html tags inside the property value, you may decorate your specific property with the AllowHtml attribute
public partial class article
{
[AllowHtml]
public string bodyofarticle { set; get; }
//other properties here
}
This will tell the framework to exclude this property from the above request validation.
I suggest you follow PascalCasing while writing C# code ( Ex : Article instead of article)
Related
I'm having some trouble with data being sent through my controller, here's a simplified example:
public ActionResult EditNote(NotesModel model)
{
model.Author = Session["UserName"].ToString();
model.Note = null;
model.Title = null;
return View(model);
}
On my views page the data shown from the model is the exact same as how it was received by the method and all changes are ignored, why?
Bigger picture:
I'm trying to have a user edit an existing note in the database, if they're the one who made it of course. based on whether or not they're the author they will either edit the existing note or create a new note, this is where the problem lies. The controller is supposed to set all the values of the model to null so that on the views page they will be empty.
Editing an existing note is no problem however emptying the model so the editing page is blank does not work.
EDIT
This is my view page:
#model WebsiteProject.Models.NotesModel
#{
ViewBag.Title = "";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section Sidebar
{
<div id="sidebarheadericon" style="background-image: url('../Content/icons/apps.png')"></div>
<div id="headertext"><h1>Welcome</h1></div>
<hr id="seperator" />
<p class="psidebar">test</p>
<p>
#Html.ActionLink("Create New", "EditNote")
</p>
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h1>NotesModel</h1>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<p class="control-label">Note by #Session["UserName"].ToString()</p>
<div class="form-group">
#Html.LabelFor(model => model.Title, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Title, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Title, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Note, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Note, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Note, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="largebtn" />
</div>
</div>
<p class="text-danger">#ViewBag.NoteViewError</p>
</div>
}
<div>
#Html.ActionLink("Back to List", "NoteApp")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Here you can see the data that is received (dummy data)
Now here you'll see that the data of the model is changed
Yet on the website it is not changed
The biggest problem isn't the Note and Title not being changed because the user can do that, but the Id and Author, which the user cannot, and should not be able to change.
This is related to the fact that you are using EditorFor:
#Html.EditorFor(model => model.Note, new { htmlAttributes = ... })
It so happens that EditorFor not only uses the Model object, it also uses ModelState which keeps a copy of all values for all Model items that were received, parsed and validated, along with any validation errors that this may have produced.
As long as ModelState has a value for that model item, it will be shown by EditorFor. The reason is that user input may be invalid, like entering 12X for an int Model property. EditorFor will show 12X if the form is re-rendered, which is coming from ModelState, and which could never come from Model.
Unwanted values can be removed by calling Remove, like this:
ModelState.Remove("Note");
On a different note, the ViewModel class that you are using here is not suited to the needs of this action method. It may be better to create a dedicated ViewModel class for it, with fewer properties, which you can then convert to the ViewModel type that the View needs.
I think you want to tell the incoming notes model is a new one or an existing one, here is some code to try,
public ActionResult EditNote(NotesModel model)
{
if(model.Id > 0) //assuming existing notes has id or any other ways you want to check
{
//save data
return View(model);
}
else //if Id has a value <= 0, return a new model with only Author set, maybe the Id (depending on how you want to generate the Id)
{
var model = new NotesModel();
model.Author = Session["UserName"].ToString();
return Viwe(model);
}
}
I use the following code for the Editing Button, but clicking on the Edit button does not post it
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "PageID,GroupID,Title,ShortDescription,Text,Autor,Tags,Visit,ImageName,ShowInSlider,CreatDateTime")] Page page,HttpPostedFileBase imgUp)
{
if (ModelState.IsValid)
{
if (imgUp != null)
{
if (page.ImageName != null)
{
System.IO.File.Delete(Server.MapPath("/PageImages/" + page.ImageName));
}
page.ImageName = Guid.NewGuid() + Path.GetExtension(imgUp.FileName);
imgUp.SaveAs(Server.MapPath("/PageImages/" + page.ImageName));
}
pageRepository.UpdatePage(page);
pageRepository.save();
return RedirectToAction("Index");
}
....
I have separate data layer and repository and I use the following code for the Editing Pages Controller, but with clicking on the Edit button does not post form. Though it works well for creation and delete btn. my view code is:
<div class="form-horizontal">
<h4>Page</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.PageID)
#Html.HiddenFor(model => model.Visit)
#Html.HiddenFor(model => model.CreatDateTime)
#Html.HiddenFor(model => model.ImageName)
<div class="form-group">
#Html.LabelFor(model => model.GroupID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("GroupID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.GroupID, "", new { #class = "text-danger" })
</div>
</div>
....
<div class="form-group">
#Html.LabelFor(model => model.ImageName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="imgUp" id="imgUp"/>
#Html.ValidationMessageFor(model => model.ImageName, "", new { #class = "text-danger" })
#if (Model.ImageName != null)
{
<img src="/PageImages/#Model.ImageName" class="thumbnail" style="max-width:150px" />
}
.....
<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>
}
i trace my code and find this eror:
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Request","time":"2018-04-25T08:10:44.3663705Z","tags":{"ai.internal.sdkVersion":"web: 2.0.0.25000","ai.device.roleInstance":"Laptop-erfan","ai.operation.name":"GET PageGroup
above horizontal form tag is this code:
#model DataLayer.Page
#{
ViewBag.Title = "Edit";}<h2>Edit</h2>#using (Html.BeginForm("Edit", "Pages", FormMethod.Post, new { enctype = "multipart/form-data" })){ #Html.AntiForgeryToken()
As mentioned in the comments it doesn't look like you have a form in your view. You can add one using:
#using (Html.BeginForm()) {
<!-- form contentshere -->
}
BeingForm has several overloads as well that you can use to change where it goes to, form method (GET/PUT) and set html attributes.
You need to add the complete form page into a Form tag.
please Use
#using (Html.BeginForm()) {
//Put your complete code inside this form...
}
It will create the Form tag with specified actions and type.
You can also specific the custom action method and type of the method as well.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Hi can you help in sending a static value of the field in another view field..
so when the user clicked the button it will directly go to the page
my view page of the static value
#using (Html.BeginForm())
{
<div class="form-horizontal">
<h4>Customer</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Price, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Price, new { htmlAttributes = new { #Value = "5", #readonly = "readonly", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Price, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Pay" class="btn btn-default" />
</div>
</div>
</div>
}
to this view
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="form-group">
#Html.LabelFor(model => model.Payment.Amount, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Payment.Amount, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Payment.Amount, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
Controller 1
public ActionResult Pay(Payment apsp)
{
decimal amount = apsp.Amount;
Payment pay = new Payment
{
Amount = amount
};
return RedirectToAction("Create");
}
Model
public decimal Amount{ get; set; }
Currently your Pay action method returns a RedirectResult, which is basically a 302 response which tells the browser to make a new HTTP GET call to the Create action method url. If you want to pass some data, you should return the view instead of this redirect result and pass the view model to the View method call.
So replace
return RedirectToAction("Create");
with
return View("Create",pay);
Also there is no reason to create a new object if you are only reading one property and assigning it to same object type.
public ActionResult Pay(Payment apsp)
{
return View("Create",apsp);
}
But from your question, It looks like your first view and second view are strongly typed to different view models. For the above code to work, Both should be strongly typed to same view model (as you are passing the same object of Payment)
Note. It is possible to pass (minimal) data via ReidrectToAction method call. Read the below post for more information about different ways to achieve that.
How do I include a model with a RedirectToAction?
I will assume that you know how the HttpPost and HttpGet work.
You can pass your viewmodel via TempData like this:
[HttpGet]
public ActionResult Pay()
{
return View(new Payment());
}
[HttpPost]
public ActionResult Pay(Payment payment)
{
TempData["Payment"] = payment;
return RedirectToAction("Create");
}
[HttpGet]
public ActionResult Create()
{
if (TempData["Payment"] == null) throw new Exception("Error");
var payment = TempData["Payment"] as Payment;
return View(payment);
}
I'm creating a webpage using MVC 5, Visual Studio, C#.
In my view I have a remark page which the user is allowed to make a remark in a text box and click "save" to save the remark in a database. However, it is saying that the value of the remark is invalid when it shouldn't be.
The error is
The value 'Testing Remark' is invalid
yet it should be valid
In my model, I have a class called Recall, which has a
public string Remark {get; set;}
In the view I have
#using (Html.BeginForm())
{
<div class="form-group">
#Html.LabelFor(model=>model.Remark, htmlAttributes: new {#class ="control-label col-md-2"})
<div class="col-md-10">
#Html.TextAreaFor(model => model.Remark, 5, 50, new { #class = "text-danger"})
#Html.validationMessageFor(model => model.Remark, "", new { #class = "text-danger"})
</div>
</div>
<div class="form-group">
<input type="submit" value="save" class="btn btn-default" />
</div>
}
In the controller
....
not putting the controller code here since it should have nothing to do with the error I'm getting.
You should use data type MultilineText if you are using a TextArea:
[DataType(DataType.MultilineText)]
public string Remark { get; set; }
Or just change the TextAreaFor to a TextBoxFor if you don't need multi line text:
#Html.TextBoxFor(model => model.Remark, new { #class = "text-danger"})
I've noticed something in the mvc default projects that made me wonder how it works. When I create a ddefault MVC Project with Individual User Accounts authentication, visual Studio scaffolds an AccountController with two "ResetPassword" Actions. One that accepts a string parameter via GET request. The Action looks like this:
// GET: /Account/ResetPassword
[AllowAnonymous]
public ActionResult ResetPassword(string code)
{
return code == null ? View("Error") : View();
}
And the View looks like this:
#model SISGRAD_MVC.Models.ResetPasswordViewModel
#{
ViewBag.Title = "Reset password";
}
<h2>#ViewBag.Title.</h2>
#using (Html.BeginForm("ResetPassword", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Reset your password.</h4>
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Code)
<div class="form-group">
#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">
#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">
#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="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Reset" />
</div>
</div>
I access the Action with the code in the URL, GET-style, and the view knows to initialize the model property from the URL. One point of interest is that this only works if I use #Html.HiddenFor(). How does this work, and how does the view know when to pull data from the URL, and when not to?
Because you method is
public ActionResult ResetPassword(string code)
the DefaultModelBinder will add the value of code to ModelState
The HiddenFor(m => m.Code) method uses values from ModelState rather that the values from the model if they exist so it will render
<input type="hidden" name="Code" id="Code" value="###" />
where ### is the value you passed to the method.
Your statement that the "view knows to initialize the model property from the URL" is not correct. The model is not initialized and is in fact null which you can test using
<div>#Model.Code</div>
which will throw an "Object reference not set to an instance of an object." exception, whereas
<div>#ViewData.ModelState["Code"].Value.AttemptedValue</div>
will display the correct value.
Side note: From your comments, the reason that DisplayFor(m => m.Code) does not show the value is that its is using the value in the ViewData (which is null because the model is null). The default display template uses the following code (refer source code)
internal static string StringTemplate(HtmlHelper html)
{
return html.Encode(html.ViewContext.ViewData.TemplateInfo.FormattedModelValue);
}
as opposed to HiddenFor(m => m.Code) which uses the following code (refer source code
default:
string attemptedValue = (string)htmlHelper.GetModelStateValue(fullName, typeof(string));
tagBuilder.MergeAttribute("value", attemptedValue ?? ((useViewData) ? htmlHelper.EvalString(fullName, format) : valueParameter), isExplicitValue);
break;
Note also that if you define a route with url: "Account/ResetPassword/{code}" then you do not need to add the hidden input in your view. It will be added as a route value by default - the BeginForm() method will render
<form action="Account/ResetPassword/###" ... >