asp.net-mvc: Adding a passwordFor to the view auto populates my fields - asp.net-mvc-4

The scenario: I am trying to add a view to Create new users by admin. The app is form authentication. There is a logged in user(admin). When a Password For is added to the view, the view automatically populates the fields with the logged in user.
The controller code:
public ActionResult Create()
{
var userViewModel = new UserViewModel();
return View(userViewModel);
}
The view code:
#model MVC4.Models.UserViewModel
#{
ViewBag.Title = "Create";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>UserVireModelcs</legend>
<div class="editor-label">
#Html.LabelFor(model => model.UserName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.UserName)
#Html.ValidationMessageFor(model => model.UserName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Password)
</div>
<div class="editor-field">
#Html.PasswordFor(model => model.Password)
#Html.ValidationMessageFor(model => model.Password)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}

What I suspect is happening here is that the application isn't pre-filling the fields, but the browser is. This is because this form looks exactly like a login prompt. (You can test this by clearing your information from the browser itself so that it doesn't auto-fill any login prompt on this site.)
What I would recommend is to semantically separate the concepts of logging in and creating a user. Basically... rename the fields. A simple view model with some more specific names would help:
public class CreateUserViewModel
{
public string NewUserUsername { get; set; }
public string NewUserPasswords { get; set; }
}
Then use that in your view:
<div class="editor-label">
#Html.LabelFor(model => model. NewUserUsername)
</div>
<div class="editor-field">
#Html.EditorFor(model => model. NewUserUsername)
#Html.ValidationMessageFor(model => model. NewUserUsername)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.NewUserPassword)
</div>
<div class="editor-field">
#Html.PasswordFor(model => model.NewUserPassword)
#Html.ValidationMessageFor(model => model.NewUserPassword)
</div>
It's a little more verbose than perhaps one might want it to be (I would agree that simpler is always better), but adding some explicit context to the naming in this case makes it more clear to the browser that this isn't a login form. Use any naming that makes sense for your needs, just make it more descriptive than Username and Password.

Related

why call to saveChanges() throws error "Object reference not set to an instance of an object."

i have the following code for view:
#model test1.Models.CustomerVM
#{
ViewBag.Title = "Create";
}
<link href="~/Content/themes/base/jquery.ui.all.css" rel="stylesheet" />
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Customer</legend>
#Html.HiddenFor(model=>model.UserId)
#Html.HiddenFor(model=>model.Id)
<div class="editor-label">
#Html.LabelFor(model => model.User)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.User)
#Html.ValidationMessageFor(model => model.User)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Password)
</div>
<div class="editor-field">
#Html.PasswordFor(model => model.Password)
#Html.ValidationMessageFor(model => model.Password)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ConfirmPassword)
</div>
<div class="editor-field">
#Html.PasswordFor(model => model.ConfirmPassword)
#Html.ValidationMessageFor(model => model.ConfirmPassword)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.NameTitle)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.NameTitle, Model.NameTitleColl)
#Html.ValidationMessageFor(model => model.NameTitle)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.FName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.FName)
#Html.ValidationMessageFor(model => model.FName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.LName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.LName)
#Html.ValidationMessageFor(model => model.LName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Gender)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Gender, Model.GenderColl)
#Html.ValidationMessageFor(model => model.Gender)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.DOB)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.DOB)
#Html.ValidationMessageFor(model => model.DOB)
</div>
#* contacts *#
<div class="editor-label">
#Html.LabelFor(model => model.AddressL1)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.AddressL1)
#Html.ValidationMessageFor(model => model.AddressL1)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AddressL2)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.AddressL2)
#Html.ValidationMessageFor(model => model.AddressL2)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Suburb)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Suburb)
#Html.ValidationMessageFor(model => model.Suburb)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Country)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Country)
#Html.ValidationMessageFor(model => model.Country)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Phone)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Phone)
#Html.ValidationMessageFor(model => model.Phone)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
<script src="~/Scripts/jquery-2.1.4.min.js"></script>
<script src="~/Scripts/jquery-ui-1.11.4.min.js"></script>
#Scripts.Render("~/bundles/jqueryval")
<script>
$(document).ready(function () {
$('#DOB').datepicker({
appendText: 'mm/dd/yyyy',
showOn: 'both',
buttonText: 'click me',
dateFormat: 'mm/dd/yy',
changeMonth: 'true',
changeYear: 'true',
yearRange: '1900:2016'
});
});
</script>
}
the view works fine displays data as it should be. but when i click Create to save record the following error throws : Object reference not set to an instance of an object This is thrown when it executes the line db.SaveChanges();
Here is the action that does the save. Note: though the view has more field but im not saving all only the ones i have stated in Create() will be saved a.k.a only data in mst_users will be saved
[HttpPost]
public ActionResult Create(CustomerVM custObject)
{
if (ModelState.IsValid)
{
mst_users user = new mst_users
{
uName=custObject.User,
password=custObject.Password,
dtCreated=DateTime.UtcNow,
isLocked=false
};
db.mst_users.Add(user);
db.SaveChanges();
}
}
when i check the receiving data to the method it has all the required data to do the save but funny thing is when it throws the exception the debugger takes the control to the the view and points to the NameTitle field.
Line 44: </div>
Line 45: <div class="editor-field">
Line 46: #Html.DropDownListFor(model => model.NameTitle, Model.NameTitleColl)
Line 47: #Html.ValidationMessageFor(model => model.NameTitle)
Line 48: </div>
here is the table that maps to Entity class mst_users
[uName] varchar
[password] varchar
[dtCreated] datetime
[dtUpdated] datetime
[isLocked] bit
here is the entity class:
here is the video
Here is a null reference error video
As you stated that:
but funny thing is when it throws the exception the debugger takes the control to the the view and points to the NameTitle field.
The problem is not exactly at SaveChanges(), but the exception actually occurs when your action is successfully executed and your same Create view is rendered again. This time, your Model or Model.NameTitleColl is null.
When you make get call to your Create action, you must be populating your CustomerVM method and returning it to view. But after making POST call call to your Create method, if you want to render the same view again, you must populate your CustomerVM again, at the end, and pass it to the view. something like:
[HttpPost]
public ActionResult Create(CustomerVM custObject)
{
if (ModelState.IsValid)
{
mst_users user = new mst_users
{
uName=custObject.User,
password=custObject.Password,
dtCreated=DateTime.UtcNow,
isLocked=false
};
db.mst_users.Add(user);
db.SaveChanges();
}
return View(custObject);
//or return View(new CustomerVM()) just to make you understand
}
UPDATE: (based on video you attached)
You are only populating User, Password and ConfirmPassword field of your CustomerVM model. And you have decorated your Address, Fname and several other properties with *[Required]* attribute. Which means, it MUST not be null when posted, (in order to make model valid). Otherwise, your model state would be invalid. You can clearly see in video, custObject contains null for required values. so exactly as expected, you ModelState.IsValid will give you false in return.
UPDATE: (based on second video you attached)
You are right, your exception occurs at db.SaveChanges() line. The reason for why your debugger takes you to view is following piece of code in your action:
try
{
....
db.SaveChanges();
}
catch()
{
return View(); // <- this line
}
so technically, exception occurs, and the control of your program is moved to your catch block. and you execute return View() in order to handle your exception and when view is rendered, Model.NameTitleColl is null. This throws another exception, which you actually see. whereas, you have skipped the orignal exception.
Reason and Solution:
From your code, I can see, you do not initialize your db object in your action, which throws the orignal exception. Please initialize the db object before you perform any action on it. You can do something like:
db = new YourDbContextNameHere(); //initialize your db object with your Dbcontext class constructor
and then do:
db.mst_users.Add(user);
db.SaveChanges();
it will work fine this way.
This NullPointerException is thrown for db or db.mst_users? In my opinion any one of them is not properly Instantiated.
Based on #Zeeshan answer, I presume your mst_users is being saved to the database the very first time you click the Create button. The problem is likely to be that you are returning same view without passing in the appropriate model that contains the Model.NameTitleColl which is used to populate the dropdown. Hence, the NullExpception.
Update 1
Your model will be invalid because most of your required fields in CustomerVM are null.
For example
the following required field
LName, FName etc are all null. in your video, this values are not provided in the view.

asp.net MVC4 selecteditem in dropdownList

How to set selecteditem in a dropdownList when editing a record? Please help me!
The below is the controller:
public ActionResult Edit(int id)
{
ViewModel model = GetViewModel(id);
return View(model);
}
The below is the view:
#model ViewModel
#{
ViewBag.Title = "Edit";
}
<h2>Edit/Copy Request</h2>
<h3></h3>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Requests</legend>
<div class="float-left">
#Html.LabelFor(model => model.Crop)
#Html.DropDownList("CropList", string.Empty)
#Html.ValidationMessageFor(model => model.Crop)
</div>
<div class="float-right">
#Html.LabelFor(model => model.Stage)
#Html.EditorFor(model => model.Stage)
#Html.ValidationMessageFor(model => model.Stage)
</div>
</fieldset>
<p>
<input type="submit" value="Save Change" />
</p>
}
The "CropList" is a selectList that is part of the ViewModel.
#Html.DropDownList("CropList", string.Empty) would get the selection list for the dropdown box. However, how to get set selectedItem of the dropdown box? It is easy with textbox:
#Html.EditorFor(model => model.Crop);
Hugh
put it in a drop down list for instead. for helpers tie items to the model
#Html.DropDownListFor(x => x.CropList, SelectList)

MVC "create view" when there is one to many relationship in model

My model is simple, one client can have many phone numbers :
I have represented this in Entity Framework
Generated client class is as below.
public partial class Client
{
public Client()
{
this.PhoneNumbers = new HashSet<PhoneNumber>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<PhoneNumber> PhoneNumbers { get; set; }
}
And now I need to create a view page for "create client". This page should have space to enter PhoneNumbers also (ex: By default there should be two text boxes to enter phone numbers)
<fieldset>
<legend>Client</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
as the above "create view" we can easily give an space for "model.Name", because it is a simple property. But how can i do something similar for collection of phone numbers..??
I know that we can achieve this with ugly javascript code, but I would like to know the best easy and simple way, that we can use with ASP.NET MVC ... ?
You have to do a few things:
First create a ViewModel that has the properties you need:
public class ClientViewModel
{
public int Id {get;set;}
public string Name {get;set;}
public PhoneNumber PhoneNumber1 {get;set;}
public PhoneNumber PhoneNumber2 {get;set;}
}
Change Create to return the ClientViewModel
[HttpGet]
public ActionResult Create()
{
return View(new ClientViewModel());
}
Map the HttpPost to use the ClientViewModel and map the values to it:
[HttpPost]
public ActionResult Create(ClientViewModel clientViewModel)
{
var client = new Client();
client.Name = clientViewModel.Name;
client.PhoneNumbers.Add(clientViewModel.PhoneNumber1);
client.PhoneNumbers.Add(clientViewModel.PhoneNumber2);
db.Clients.Add(client);
db.SaveChanges();
return RedirectToAction("Index", "Client");
}
Then, finally, modify your view:
<fieldset>
<legend>Client</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PhoneNumber1.Number)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PhoneNumber1.Number)
#Html.ValidationMessageFor(model => model.PhoneNumber1.Number)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PhoneNumber2.Number)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PhoneNumber2.Number)
#Html.ValidationMessageFor(model => model.PhoneNumber2.Number)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
For the collection you can use something like this:
#for(int i = 0; i < Model.PhoneNumbers.Count; i++)
{
<div class="editor-field">
#Html.EditorFor(model => model.PhoneNumbers[i])
#Html.ValidationMessageFor(model => model.PhoneNumbers[i])
</div>
}

checkbox postback in Mvc 4

What is a best usag Razor checkbox with postback?
for examle I have a class as follow
public class Person
{
public string Name { get; set; }
public string SurName { get; set; }
public bool hi { get; set; }
}
and a view(with script):
<script type="text/javascript">
$(function () {
$('#hi').change(function () {
$(this).closest("form").submit();
});
});
</script>
#using (Html.BeginForm(FormMethod.Post))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Person</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.SurName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.SurName)
#Html.ValidationMessageFor(model => model.SurName)
</div>
#Html.CheckBoxFor(model => model.hi)
</fieldset>
}
I want postback when I click "hi" checkbox. How can I do it?
a bit jQuery:
$(function(){
$('#hi').change(function () {
$(this).closest("form").submit();
});
});
I haven't tried this out yet. But on the top of my mind, I would add a submit button within the Html.BeginForm(FormMethod.Post) curly braces, and add a style to it to display=none. In other words, it'l be hidden. Then I would add a checkbox event such as onValueChange using jquery (or maybe onClick maybe?, not sure of all of the events by heart.) Within the event block i'd simulate the button click by $('#btnInvisibleButton').Click(); Note that i had trouble executing .Clic() on Safari I think (there's a way around it by adding additional code specific to that browser , so you should test your code on all browsers.
Try this code, just make sure that the submit button is within the form tag:
$('#yourCheckBox').change(function () {
$("#btnInvisibleButton").click();
});

How to upload Photos/ Images in Asp.Net 4.o Project

I want to add upload photo features in my MVC 4.0 Project, Please can you tell me how can I do that. I am using MVC 4.o and for Photo option i want to give file / image upload. Here is my Code
#model WebCart.Category
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm("Create", "Category", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Category</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Title)
#Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Photo)
</div>
<div class="editor-field">
<input name="PhotoFile" id="File" type="file"/>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(Category category)
{
if (ModelState.IsValid)
{
db.Categories.AddObject(category);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(category);
}
Your controller action could take an additional PhotoFile argument:
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(Category category, HttpPostedFileBase photoFile)
{
if (ModelState.IsValid)
{
// you could manipulate the PhotoFile parameter here
// for example let's store the uploaded file to a folder on the server
if (photoFile != null && photoFile.ContentLength > 0)
{
var fileName = Path.GetFileName(photoFile.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
photoFile.SaveAs(path);
}
db.Categories.AddObject(category);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(category);
}
Or if you want to read the uploaded file as a byte array you could use the following:
byte[] photo = new byte[photoFile.InputStream.Length];
photoFile.InputStream.Read(photo, 0, photo.Length);
// Now you could assign the byte array to some property of your model
// and persist it into the database (even if this is a bad practice -
// it would be more correct to store the photo on the file system and
// only store the full path to the photo in the database)
A must read article for uploading files in ASP.NET MVC is the following: http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx