MVC - View without model but has one field - asp.net-mvc

I have a page which will require a password field only. User has to enter his password then submit. Is it possible to create a view for that without a model? I asked because if I need to create a model then it will have a password property only. I hope there is a simple way for this simple page.

If you don't want to create View Model then it is completely fine. You can loose some benefit like automatic client side validation ( data annotation). It means you have to do all validation by your self in client side and later on server side.
This is simple way you can do that.
Your controller code something look like this.
public ActionResult AcceptPasswordOnly(string Password)
{
// Do your validation if want password back to field if validation failed then set in ViewData["Password"] = Password
return View();
}
Your view code something look like this.
#using (Html.BeginForm("AcceptPasswordOnly", "Home"))
{
<div>Enter Passowrd :</div> #Html.TextBox("Password" , ViewData["Password"] ?? "")
<input type="submit" />
}
Note: Just remember that #Html.TextBox first argument is name and controller method parameter must same so you can access directly.
This way you can do directly without creating model and just using primitive datatype.

Related

How do I pass the userId into the model ASP.NET MVC?

I've had a thorough search around but really can't find anything addressing the scenario I'm facing (oddly because I'd have thought it's quite a common thing to do).
Background
I'm creating an application with ASP.NET MVC 4 and Entity Framework 5 Code First. For the purpose of this question, think of it as a blogging application with posts and users.
Project
The post model requires that every post have a corresponding UserId.
With the ASP.NET MVC 4 Membership it is easy to find the username of the person logged in with
User.Identity.Name.
This isn't ideal, we want the ID, but a query such as this can search the db for the name and get the ID.
db.UserProfiles.Single(a => a.UserName == User.Identity.Name);
Problem
The problem arises when trying to create a post. Model.IsValid is false, as no UserId is being passed in from the view. Obviously, as the user isn't expected to enter their ID.
I've tried putting the ID value into the ViewBag and using a #Html.Hidden() field in the view, however I've had no success with this. Model.IsValid always returns false.
Should this information be input through the create view? Or should it be done directly in the controller? Its quite a frustrating problem as I have the information and just need to figure how to pass it into the model.
CONTROLLER CODE
This is basically just the default scaffolded code. The commented code is how I tried setting the model value directly from the controller, however that was little more than trial and error.
//
// POST: /Post/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Post post)
{
if (ModelState.IsValid)
{
//var userId = db.UserProfiles.Single(a => a.UserName == User.Identity.Name);
//post.User.UserId = userId.UserId;
db.Posts.Add(post);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(post);
}
Be careful with hidden fields. Anyone could put whatever value they want in that field (i.e. they could spoof another user). You'd be better off caching the ID in the session at login, and using that value.
This is a typical case where you want to create an EditModel as a data transfer object (DTO) between your view and controller layers.
Create a class BlogPostEditModel that has all properties you need the user to fill in when creating a new blog post. Then, map this type (e.g. using AutoMapper) to your BlogPost entity, and fill in the user ID as well.
To use built-in validation such as Model.IsValid(), put the data annotations attributes on the DTO instead.
Honestly, I would have the value assigned via the controller. If you had someone messing with your html via Firebug, they could actually change the id before it was passed and submitted to your form. I would remove it from your Create view and submit from the controller.

How to pass id value to controller instead from query string while getting details of page in MVC

I want to pass insured id to controller while getting insured details which looks like:
// GET: /Insured/Details/123456789
But I don't want to pass this id number 123456789 in query string for security reasons.
Can somebody suggest me the best way. I am new to MVC.
Thanks
Try submitting the value as a hidden parameter via POST. You'll need to use a form to do POST submits though. You can't use links.
<form method="POST" action="/Insured/Details">
<input type="hidden" name="insuredid" value="123456789"/>
<input type="submit"/>
</form>
You would then get the value via request parameter. If using Java servlets, it would look something like this:
String myInsuredId = request.getParameter("insuredid");
I imagine it would look similar to other platforms as well.
NOTE: Although passing values as hidden parameters hides the data from view, this does not prevent people from sniffing the submitted data or checking the HTML source of your page. If you really want to make this secure, you'll need to use some form of encryption/security. Try looking into HTTPS posts.
You need to sanitize your input in the controller, for example if the customer is logged in you could check that the ID passed to the controller truly belongs to the customer.
Anything that is passable in request (whether it's POST or GET) is spoofable.
You should also look into serving the page over HTTPS.
E.g. (asp.net MVC / C#)
public ActionResult Details(string id)
{
if (Check(id) == false)
{
// Handle invalid input
throw new HttpException(404, "HTTP/1.1 404 Not Found");
}
// create the model
...
}

How to handle hidden fields in MVC forms?

I have a FormViewModel that handles different fields. Many of them have not to be presented to the user (such as modified_date, current_user_id) so I am using hidden fields to respect the FormViewModel structure. When submitted they are passed to the controller's action and correctly saved to the DB but I'm asking: is it the best way to do in ASPNET MVC? I would have preferred to define them in FormViewModel and using only the fields to be modified instead of showing also the non-modifiable as hidden fields.
Is there a better way to do it?
If these fields are not being touched by the user than I would do this;
Create a FormViewModel with only the fields that are relevant. Also the primary key.
The primary key still needs to be on the page me thinks.
Then in the controller you accept the FormViewModel as the argument, you then load the actual model and update, validate fields as required and save the model.
The above is simplistic and you'll have more layers but you should get the idea
I think you can do a few things to make your life a little easier:
Let the URL (and the routing mechanism) give you the id (the primary key of whatever you are trying to edit)
You can have a URL like '/Student/Edit/1' Routing will ensure that your Action method gets the id value directly.
Have 2 action methods to handle your request. One decorated with [HttpGet] to render the initial form to the user (where you just retrieve your object from the repository and pass it on to your View) and a [HttpPost] one to actually handle the post back from the user.
The second method could look something like:
[HttpPost]
[ActionName("Edit")]
public ActionResult EditPost(int id) {
...your code here...
}
Retrieve the actual record from the repository/store based on the id passed in.
Use the UpdateModel function to apply the changes to the database record and pass on the record back to your repository layer to store it back in the database.
However, in a real world application, you will probably want separation of concerns and decoupling between your repository and your view layer (ASP.NET MVC.)
If they are part of the model, the method you are using is perfectly fine. You even have a helper method in HtmlHelper.HiddenFor to output the hidden field for you. However, if the values are something like modified date or current user, you'd might be better suited passing those along from your controller to a DTO for your data layer. I'm making some assumptions about what you're doing for data access, though.
The risk with storing data which shouldn't be modified in hidden fields is that it can be modified using a browsers built in/extension developer tools. Upon post these changes will be saved to your database (if that's how you're handling the action).
To protect hidden fields you can use the MVC Security Extensions project https://mvcsecurity.codeplex.com.
Say the field you want to protect is Id...
On you controller post method add:
[ValidateAntiModelInjection("Id")]
Within your view add:
#Html.AntiModelInjectionFor(m => m.Id)
#Html.HiddenFor(m => m.Id)
On post your Id field will be validated.
Create a FormViewModel with only the fields that are relevant. Also the primary key.
The primary key still needs to be on the page me thinks.
Then in the controller you accept the FormViewModel as the argument, you then load the actual model and update, validate fields as required and save the model.
The above is simplistic and you'll have more layers but you should get the idea

Why does the default model binder not validate fields when they are not in form data?

Let's say you have simple object like this :
public class MyObject {
public int Test { get; set; }
}
And you count on the default model binder to make sure the user does not leave the "Test" field empty when posting a form like below :
<form method="post" action="/test">
<p>
<%=Html.TextBox("Test") %>
<%=Html.ValidationMessage("Test") %>
</p>
<input id="Submit1" type="submit" value="submit" />
</form>
And this action :
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Test(MyObject o) {
return View();
}
This all works as expected when the form data contains a key for "Test" (like "Test=val" or "Test=")
But if the key is not in the form data, then the validation doesn't occur. So in case of an empty post request or a request with a data like AnotherField=foo the property on the model object defaults to the type's default value (in this case 0). And ModelState.IsValid returns true.
This is, IMO, not the behaviour one would expect.
So what do you suggest to change this behaviour?
Edit :
Keep in mind that a malicious user can just tamper the form data easily with FireBug or Tamper Data plugin to pass the default model binder's validations, which could cause some security problems.
It is not validating the fields by design, unfortunately. Please take a look at this Codeplex issue that I've found and commented on.
It is really unfortunate, that MS has decided this is the correct behaviour for their model binder.
I believe the default model binder should validate the whole entity instead of just the posted data.
You might consider using xVal to perform the necessary mix of client- and server-side validation. With it, you can add an attribute to your Test property dictating what sort of validation rules (required, regex validation, etc.) apply to it and then, with a little more work, get it to generate JavaScript rules for you as well as pretty easily perform model validation.
You're already aware that you're violating a rule of development - never trust client input. There's really no way around it.
Client-side validation (preventing a round trip to find out that there's an error) is nice-to-have, server-side validation verifying that things truly are in order is a must-have.
i hope its by design because I am about to start relying on this behavior!
in one instance i have two controls which post back the following fields :
ShippingAddress.FirstName
ShippingAddress.LastName
ShippingAddress.Line1
ShippingAddress.Line2
BillingAddress.Email
BillingAddress.FirstName
BillingAddress.LastName
BillingAddress.Line1
BillingAddress.Line2
Note: Billing Address does not have email displayed, even though the underlying model of course still has it
If I have Email as a [Required] data annotation in my model then it will only complain when it is missing from Billing Address.
But I definitely see your point! I'm just relying on it for this one scenario here!
After researching all the different ways to get the form values into my controller methods, I discovered that the "safest" was to explicitly define each form field as a parameter to the controller. A side effect is that if a form does NOT have one of the fields, it will throw an exception - which would solve your problem.

ASP.NET MVC Form repopulation

I have a controller with two actions:
[AcceptVerbs("GET")]
public ActionResult Add()
{
PrepareViewDataForAddAction();
return View();
}
[AcceptVerbs("POST")]
public ActionResult Add([GigBinderAttribute]Gig gig, FormCollection formCollection)
{
if (ViewData.ModelState.IsValid)
{
GigManager.Save(gig);
return RedirectToAction("Index", gig.ID);
}
PrepareViewDataForAddAction();
return View(gig);
}
As you can see, when the form posts its data, the Add action uses a GigBinder (An implemenation of IModelBinder)
In this binder I have:
if (int.TryParse(bindingContext.HttpContext.Request.Form["StartDate.Hour"], out hour))
{
gig.StartDate.Hour = hour;
}
else
{
bindingContext.ModelState.AddModelError("Doors", "You need to tell us when the doors open");
}
The form contains a text box with id "StartDate.Hour".
As you can see above, the GigBinder tests to see that the user has typed in an integer into the textbox with id "StartDate.Hour". If not, a model error is added to the modelstate using AddModelError.
Since the gigs property gigs.StartDate.Hour is strongly typed, I cannot set its value to, for example, "TEST" if the user has typed this into the forms textbox.
Hence, I cant set the value of gigs.StartDate.Hour since the user has entered a string rather than an integer.
Since the Add Action returns the view and passes the model (return View(gig);) if the modelstate is invalid, when the form is re-displayed with validation mssages, the value "TEST" is not displayed in the textbox. Instead, it will be the default value of gig.StartDate.Hour.
How do I get round this problem? I really stuck!
I think the problem is that your ViewModel does not match closely enough with your View. It's really important in MVC that your ViewModel matches your View as closely as possible.
In your ViewModel you're assuming an integer, but in your View you're using a TextBox to render the property, which will allow any kind of text. There's a mismatch here and the difficulties you are experiencing trying to map them is a symptom of the mismatch.
I think you should either:
1. Change the type of the ViewModel property to string and then do validation in your controller to ensure the string entered is actually a number or:
2. Change the control that the View renders to a control that will only allow a number to be entered via a custom control or Javascript validation (as #Qun Wang recommends)
Personally, I'd recommend option 1. That way the ViewModel is not dependent on the View implementation.
Could you do this in your PrepareViewDataForAddAction method?..
if (!ViewData.ModelState.IsValid)
{
ViewData["StartDate.Hour"] = "Error";
}
The other fields on the form will still populate based on the properties of the Gig object.
I think you need to do some basic client side validation first.
don't allow it to post to the server.

Resources