Pipe character causes "unexpected token" error in Html.BeginForm - asp.net-mvc-4

I am trying to recreate the HTML design of an existing login form for use in an MVC4 program. Most of this is fine, however when I try to enter a pipe character ( | ) between two elements, it throws an error "unexpected token". You can see it there at the bottom, after the button and before the anchor. Any ideas why this is an error? Is there a way to fix it? (Other than removing the pipe character?)
#using (Html.BeginForm("Login", "AccountController", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { #class = "form-login form-wrapper form-narrow" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<h3 class="title-divider"><span>Login</span> <small>Not signed up? #Html.ActionLink("Sign Up Here.", "Register")</small></h3>
#Html.LabelFor(m => m.UserName)
#Html.TextBoxFor(m => m.UserName, new { #class = "input-block-level" } )
#Html.ValidationMessageFor(m => m.UserName)
#Html.LabelFor(m => m.Password)
#Html.PasswordFor(m => m.Password, new { #class = "input-block-level" })
#Html.ValidationMessageFor(m => m.Password)
#Html.LabelFor(m => m.RememberMe, new { #class = "checkbox" })
#Html.CheckBoxFor(m => m.RememberMe)
<button class="btn btn-primary" type="submit" value="Log in" >Sign in</button>
| Forgotten Password?
}

Put it inside <text> tags or use the #: operator
<text>|</text>
or
#:|
Inside the using statement, you are actually in a razor code block, so anything not inside an html tag or preceded by the #: operator will be read as server code.

Related

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

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.

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.

Password is visible when i post the form using #Html.PasswordFor

When i check in firefox i can i see my password.
I am using the following code
#using (Html.BeginForm("Login", "Account", FormMethod.Post, new { #class = "navbar-form navbar-left", #id = "loginform" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="form-group form-header input-group-lg">
#Html.TextBoxFor(m => m.UserName, htmlAttributes: new { #class = "form-control", #placeholder = "Email:" })
#Html.ValidationMessageFor(m => m.UserName)
</div>
<div class="form-group form-header input-group-lg">
#Html.PasswordFor(m => m.Password, htmlAttributes: new { #class = "form-control", #placeholder = "Password:" })
#Html.ValidationMessageFor(m => m.Password)
</div>
<button class="btn btn-danger btn-lg" type="submit">Login</button>
<div class="remember">
#Html.CheckBoxFor(m => m.RememberMe, htmlAttributes: new { #id = "login-remember" })
#Html.LabelFor(m => m.RememberMe)
</div>
}
The password will always be sent in plain text in the post body. #Html.PasswordFor only obscures the input box on the screen to prevent people looking over the user's shoulder and knowing their password.
This is why you should only submit secure information through an https page: this way it will be encrypted during transmission from your computer to the remote server. It is good practice to make sure during the initial page GET that the page is on https, and if not then redirect the user to the https url for the page.

Cannot pass SelectedValue and Text to Controller for a KendoUIDropDownListFor widget

This works fine if I don't use any KendoUI functionality and am able to pass it easily using a regular Html.DropDownListfor helper (seen as comments in the code). The Description and the StatusID both do not come through.
How can I pass these values to the controller after selecting them in the dropdown list and then clicking enter with the KendoUI extension?
If I uncomment the Value and Text properties, I get "Object not set to an instance of an Object".
#using (Html.BeginForm("AddSingleStatus", "Status", new AjaxOptions { HttpMethod = "POST", }))
{
#Html.ValidationSummary(true)
<table>
<tr>
<td>
<div class="display-label">
#Html.LabelFor(model => Model.Description);
</div>
<div class="display-label" style="display: none;">
#Html.HiddenFor(model => Model.Description)
</div>
<div class="editor-field">
#(Html.Kendo().DropDownListFor(model => Model.StatusID)
.Name("statusDropDownList")
.DataTextField("Description")
.DataValueField("StatusID")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("ReadDDL", "Status");
})
.ServerFiltering(false);
})
.OptionLabel("Select a status")
.SelectedIndex(0)
.Events(e => e
.Change("dropdownlist_change")
)
)
#* #Html.DropDownListFor(model => Model.StatusID, new SelectList((YeagerTechModel.Status[])ViewData["statuses"], "StatusID", "Description"));*#
#*#Html.ValidationMessageFor(model => Model.StatusID)*#
</div>
</td>
</tr>
<tr>
<td>
<input type="submit" id="ddlSubmit" value='#Resources.Add' />
</td>
</tr>
</table>
}
<script type="text/javascript">
function dropdownlist_change()
{
var dropdownlist = $("#statusDropDownList").data("kendoDropDownList");
dropdownlist.bind("change", function (e)
{
var value = dropdownlist.value();
});
}
</script>

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