Controller is ignoring data changes? - c#

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);
}
}

Related

How to delete an item from database without actually deleting it?

I have been working on an ASP.NET MVC 5 web application using Entity Framework 6 as an assignment for my Business Programming II class. Despite the fact that I know very little about programming, I have been making progress, but I have run into trouble. I am supposed to write CRUD operations for an online storefront based on the Northwind Traders database. I already have working code for reading from the database as well as adding and updating items in the database. Where I'm struggling is deleting items. The following requirement is listed in the assignment description:
Delete a product by making it discontinued so that the information is displayed in the database. Do NOT actually delete a product from the database.
I've tried a couple things to try and make this work, but all have failed for various reasons.
Here's the code to my current Delete View (ignore any strange HTML formatting decisions, right now I'm focused on getting this functional):
#model NWTradersWeb.Models.Product
#{
ViewBag.Title = "Delete";
}
<h2>Delete</h2>
<h3>Are you sure you want to delete this?</h3>
<div>
<h4>Product: #Html.DisplayFor(model => model.ProductName)</h4>
<hr />
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-actions">
<input type="submit" value="Yes" class="btn btn-dark" /> |
#Html.ActionLink("Back to List", "Index")
</div>
}
</div>
I have tried editing my ProductsController.cs to manually set the Discontinued attribute to true as follows:
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product product = db.Products.Find(id);
if (product == null)
{
return HttpNotFound();
}
return View(product);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Product product = db.Products.Find(id);
product.Discontinued = true;
db.SaveChanges();
return RedirectToAction("Index");
}
This works, but if I run the Edit operation on the same product I'm unable to undo the change. I can deselect the Discontinued checkbox but it does not save after I submit the changes and the Index page still shows the product as discontinued.
Here's my code for the Edit View and corresponding ProductsController.cs methods, I'm unsure if these have anything to do with my problem but I will include them anyway:
View:
#model NWTradersWeb.Models.Product
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Product: #Html.DisplayFor(model => model.ProductName)</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.ProductID)
<div class="form-group">
#Html.LabelFor(model => model.SupplierID, "SupplierID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("SupplierID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.SupplierID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CategoryID, "CategoryID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("CategoryID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CategoryID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.QuantityPerUnit, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.QuantityPerUnit, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.QuantityPerUnit, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UnitPrice, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UnitPrice, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UnitPrice, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UnitsInStock, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UnitsInStock, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UnitsInStock, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UnitsOnOrder, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UnitsOnOrder, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UnitsOnOrder, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ReorderLevel, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ReorderLevel, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ReorderLevel, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Discontinued, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Discontinued)
#Html.ValidationMessageFor(model => model.Discontinued, "", new { #class = "text-danger" })
</div>
</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>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Controller Methods:
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product product = db.Products.Find(id);
if (product == null)
{
return HttpNotFound();
}
ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName", product.CategoryID);
ViewBag.SupplierID = new SelectList(db.Suppliers, "SupplierID", "CompanyName", product.SupplierID);
return View(product);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ProductID,ProductName,SupplierID,CategoryID,QuantityPerUnit,UnitPrice,UnitsInStock,UnitsOnOrder,ReorderLevel,Discontinued")] Product product)
{
if (ModelState.IsValid)
{
db.Entry(product).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName", product.CategoryID);
ViewBag.SupplierID = new SelectList(db.Suppliers, "SupplierID", "CompanyName", product.SupplierID);
return View(product);
}
My professor also alluded to making the Delete operation redirect to a simpler Edit page where we could toggle the Discontinued attribute. I think he may be alluding to a partial view but we have not covered that to my knowledge.
Please note: I consider myself a novice when it comes to programming. I've taken other classes but the instructors focused more on syntax than concepts and as such my foundation is incredibly weak. I might be clueless about certain things that other people take for granted. I want to go back and study the fundamentals after I graduate and self-study, but this is a required class for a degree that is almost completely unrelated to programming. Any tips, hints, even a nudge in the right direction would be greatly appreciated.
Your Delete logic seems fine. What I would look at in more detail is your Edit.
Overall I am not a fan of ever passing Entities between the server and the view, especially accepting an entity from the view. This is generally a bad practice because you are trusting the data coming from the view, which can easily be tampered with. The same when passing data from a view to server, this can lead to accidentally exposing more information about your domain (and performance issues) just by having some "sloppy" JavaScript or such converting the model into a JSON model to inspect client-side. The recent case of the journalist being accused of "hacking" because they found extra information via the browser debugger in a Missouri government website outlines the kind of nonsense that can come up when server-side code has the potential to send far too much detail to a browser.
In any case, in your Edit method when you accept the bound Product after deactivating the Discontinued flag, what values are in that Entity model? For instance if you use Delete to set Discontinued to "True", then go to the Edit view for that product and un-check that input control and submit the form, in your "product" coming in the Edit page, what is the state of the product.Discontinued?
If the value is still "True" then there is a potential problem with your page binding where the EditorFor is not linking to that flag properly or the value is not deserializing into the Product entity. (a private or missing setter?)
If it is coming back with what should be the correct value, then I would look at changing how you update entities. Code like this:
db.Entry(product).State = EntityState.Modified;
db.SaveChanges();
... is inherently dangerous as "product" is not an entity, it is a deserialized set of values used to populate an entity class. Ideally when updating data you would provide a ViewModel that won't be confused with an Entity class and contain just the fields that are allowed to be updated. Using your current code though with the entity class serving as that view model I would suggest something more like:
var dataProduct = db.Products.Single(x => x.Id == product.Id);
dataProduct.ProductName = product.ProductName;
dataProduct.Discontinued = product.Discontinued;
// ...
db.SaveChanges();
When it comes to possibly allowing the user to change FKs for things like categories, then you should eager load those relationships, compared the FK IDs then load and re-associate those "new" relationships in the entity loaded from data state. (Don't just replace the FK values.)
The reason for doing this rather than attaching and setting the state to modified:
We perform a validation when loading the entity. If we get back an Id that doesn't exist, we can handle that exception. We can also filter data to ensure that the current user actually has permission to see the requested ID and can end a session if it looks like someone is tampering with data.
We only update values that we allow to change, not everything in the entity. We can also validate to ensure that the values provided are fit for purpose before making changes.
When copying values across, EF will only generate UPDATE statements for values that actually change if any actually change. Attaching and setting the entity state to Modified or using Update will always generate an UPDATE statement replacing all values whether anything changed or not. (can have negative impacts on triggers or hooks in the DbContext for things like Auditing)

c# MVC code for the Editing Button, but clicking on the Edit button does not post it

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.

How to pass a static value of field(View1) to another field in (View2) in ASP.Net [closed]

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);
}

How to auto fill fields in a form using #Html.EditorFor in ASP.net MVC 5?

I'm using an autogenerated form from visual studio for asp.net mvc 5 that saves information to a database. It's the create view with the standard scaffolding etc from asp.net with entity framework.
I like the way the form looks, but I need one field (datecreated) to at least be auto filled, (but preferably autofilled and hidden). The problem is I don't understand the autogenerated code at all and my efforts to look it up have not been successful. Nor have my efforts to understand it. I'm still a beginner with html helpers, which I think these are.
Here is the form element I am working with. The part in the middle is the part I need to change to autofill (the date created field), I think the relevant part is changing the EditorFor. but I don't know:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>New Patient:</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
... //other form items removed for simplicity
<div class="form-group">
#Html.LabelFor(model => model.DateCreated,"Date Created", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DateCreated, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DateCreated, "", new { #class = "text-danger" })
</div>
</div>
... //more items left out for simplicity
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
}
And the auto generated controller for this part looks like this:
// GET: Subjects/Create
public ActionResult Create()
{
return View();
}
// POST: Subjects/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,Name,DOB,Male,Female,Address,City,ZIP,PhoneHome,PhoneCell,Email,EmergencyContact,EmergencyContactPhone,EmergencyContactRelationship,ReferredBy,DateCreated,Allergy,AllergyDescription,HighBloodPressure,LowBloodPressure,HeartCondition,Diabetes,Anemia,HighCholesterol,Pacemaker,Epilepsy,Pregnant,Cancer,STD,Pain,PainDescription,Headache,HeadacheDescription,CommonCold,HighBloodPressureConcern,Stress,Depression,Sleep,Menstruation,Fertility,WeightControl,Other")] Subject subject)
{
if (ModelState.IsValid)
{
db.SubjectDatabase.Add(subject);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(subject);
}
If you dont know how I can autofill and or hide the form element datecreated, could you please point me to where I might learn to figure this out myself. I think I am reasonable at programming, I just don't understand html helpers well, or the bind function in the controller.
Remove this part from your View
<div class="form-group">
#Html.LabelFor(model => model.DateCreated,"Date Created", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DateCreated, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DateCreated, "", new { #class = "text-danger" })
</div>
</div>
And then, inside your Controller remove DateCreated from Bind attribute and assign DateCreated property:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,Name,DOB,Male,Female,Address,City,ZIP,PhoneHome,PhoneCell,Email,EmergencyContact,EmergencyContactPhone,EmergencyContactRelationship,ReferredBy,Allergy,AllergyDescription,HighBloodPressure,LowBloodPressure,HeartCondition,Diabetes,Anemia,HighCholesterol,Pacemaker,Epilepsy,Pregnant,Cancer,STD,Pain,PainDescription,Headache,HeadacheDescription,CommonCold,HighBloodPressureConcern,Stress,Depression,Sleep,Menstruation,Fertility,WeightControl,Other")] Subject subject)
{
if (ModelState.IsValid)
{
subject.DateCreated = DateTime.Now; //if you want UTC time, use DateTime.UtcNow
db.SubjectDatabase.Add(subject);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(subject);
}
The #Value can also be used to prefill in spots by using #Html.EditorFor:
Example:
#Html.EditorFor(c => c.Propertyname, new { #Value = "5" })
There is more information to be found at:
Html.EditorFor Set Default Value

Passing parameter from url to view

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/###" ... >

Categories

Resources