I want to call model in layout for use a validation in empty text field for return a error to gust user if any fields are empty. i have a code layout
#using (Html.BeginForm("Sending", "Home"))
{
<form method="post" id="contactfrm" role="form">
<div class="col-sm-4">
<div class="form-group">
<label for="name">Name</label>
#Html.TextBoxFor("Name", null, new { id = "name", #class = "form-control", placeholder = "Enter name", title = "Please enter your name (at least 2 characters)" })
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="form-group">
<label for="email">Email</label>
#Html.TextBoxFor("Email", null, new { id = "email", #class = "form-control", placeholder = "Enter email", title = "Please enter a valid email address)" })
#Html.ValidationMessageFor(model => model.Email)
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label for="comments">Comments</label>
#Html.TextArea("Comment", null, new { id = "comments", #class = "form-control", TextMode = "MultiLine", Columns = "3", Rows = "5", placeholder = "Write you message here...", title = "Please enter your message (at least 10 characters)", Style = "resize:none" })
#Html.ValidationMessageFor(model => model.Comment)
</div>
<button name="submit" type="submit" class="btn btn-lg btn-primary" id="submit">Send Your Message</button>
<div class="result"></div>
</div>
</form>
}
i want to call sending.cs model for use in #Html.ValidationMessageFor(model => model.Name)
How can i call Model in layout?
Thank you
add your model to your View page like this
#model nameOfModel
and use it like this
#Html.ValidationMessageFor(model => model.Name)
and if you want to use only a porperty of it do it like this
#Model.nameOfproperty
Related
I have few textbox that validates when its empty, but they dont work well. Below is my logic from the model to view, what could i be missing? Currently these textbox dont seem to work and no error when i inspect from the browser. The application is on asp.net mvc using bootstrap.
[DataType(DataType.EmailAddress)]
[Required(ErrorMessage = "This field is required")]
[RegularExpression(#"^\w + ([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$")]
public string Email { get; set; }
// View
<div class="row">
<label for"Email">Email:</label>
<div class="input-group col-md-4 col-md-offset-2 col-sm-2 col-xs-2">
<div class="input-group pull-right">
#Html.TextBoxFor(m => m.Email, new { #class = "form-control", type = "text", id = "email", autofocus = "autofocus", placeholder = "example#example.com", required = "required" })
#Html.ValidationMessageFor(m => m.Email, " ", new { #class = "text-danger" })
<div class="input-group-append">
<div class="input-group-text">
</div>
</div>
</div>
</div>
</div>
NB: even if i use #html.EditorBoxFor(m=>m.Email, new {Form...}) still nothing and no error.
I have a table view with list of roles and an action link to create new roles. Below is my roles.cshtml page
#model List<ExpenCare.Models.CompanyRole>
<div class="row">
#Html.Partial("_RightSidePane")
<div class="col-10 col-sm-8 col-xs-8 col-md-10">
<div class="tab-content" id="nav-tabContent">
<div class="tab-pane fade" id="list-Roles-Content" role="tabpanel" aria-labelledby="list-Roles"></div>
#using (#Html.BeginForm("UpdateRoles", "Admin", FormMethod.Post))
{
<table class="table">
<tr>
<th>
Name
</th>
<th>
Enable
</th>
</tr>
#for (var i = 0; i < Model.Count(); i++)
{
<tr>
<td>
#Html.HiddenFor(m => m[i].Id)
#Html.HiddenFor(m => m[i].Name)
#Html.DisplayFor(m => m[i].Name)
</td>
<td>
#Html.EditorFor(m => m[i].Enabled, new { #checked = "checked" })
</td>
</tr>
}
</table>
<p><input type="submit" value="Save Changes" /></p>
<p style="color:green; font-size:12px;">#ViewBag.Message</p>
<p>
#Html.ActionLink("Create new Roles", "ViewCreateRoles", "Admin", null, new { id = "CreateRoles", #class = "appao-btn" })
</p>
}
</div>
</div>
</div>
"Create new roles" button calls to ViewCreateRoles method in admin controller, which stated below.
public ActionResult ViewCreateRoles()
{
return View("Roles/CreateRoles");
}
In CreateRoles.cshtml page user can create a role and submit. when submitting it redirects to action CreateRoles in the same admin controller.
#model ExpenCare.Models.CompanyRole
#{
ViewBag.Title = "CreateRoles";
}
<div class="row">
#Html.Partial("_RightSidePane")
<div class="col-10 col-sm-8 col-xs-8 col-md-10">
<div class="tab-content" id="nav-tabContent">
<div class="tab-pane fade show active" id="list-Profile-Content" role="tabpanel" aria-labelledby="list-Profile">
#using (Html.BeginForm("CreateRoles", "Admin", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Enabled, "Enable", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Enabled)
#Html.ValidationMessageFor(model => model.Enabled, "", new { #class = "text-danger" })
</div>
</div>
</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>
}
</div>
</div>
</div>
</div>
Below is the CreateRoles methodin admin controller.
public ActionResult CreateRoles(CompanyRole role)
{
List<CompanyRole> roles;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:1888/api/");
var responseTask = client.PostAsJsonAsync("CompanyRoles", role);
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsAsync<List<CompanyRole>>();
readTask.Wait();
roles = readTask.Result;
return View("Roles/Roles", model: roles);
}
else
{
ViewBag.Message = "not updated.";
return View("Roles/CreateRoles");
}
}
After creating a role on success user is redirecting to roles.cshtml mentioned above which shows all the roles. My problem is that my process of adding a role (go to roles page-> create new role-> redirect to roles page) is working fine. But just after redirecting to the roles page I get "An exception of type 'System.Web.Http.HttpResponseException' occurred in ExpenCare.dll but was not handled in user code" error in my web api which is getting called in CreateRoles. when I debug the process I see that after going to "Dispose" method of admin contoller "CreateRoles" method is getting called again and null "CompanyRole role" data is passed to the web API. I dunno how it is getting called again. I checked in google and tried removing all "#" from href and src of my view and layout pages, but it is still not working. I can't find why the same method is getting called twice without the button click.
I have an MVC application that allows customers to log in and submit any queries they are experiencing, they enter their name and describe their issue.This query is then sent to our support email address via our server email, in doing so I need to include the user's logged in email address as a string in the email. I've tried a few ways but I experience run time error as the email field returns null.
My controller:This is in my controller method for the email
Email.Body = $"<p><b>Name:</b> {support.UserNameSurname}</p> <p><b>Email:</b> {support.Email=User.Identity.GetUserName()}</p> <p><b>Message:</b> {support.SupportMessage}</p>";
The View
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="col-sm-offset-3 col-sm-6">
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.UserNameSurname, "Full Name" , htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-9">
#Html.EditorFor(model => model.UserNameSurname, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UserNameSurname, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SupportMessage,"Describe Issue", htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-9">
#Html.TextAreaFor(model => model.SupportMessage, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SupportMessage, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Request Help" class="btn btn-default" style="background-color: #0a9dbd;-webkit-text-fill-color: white; border-color: #0a9dbd; height: 40px; float:right;" />
</div>
<div>
#Html.ActionLink("Back to List", "CustomerView")
</div>
</div>
</div>
</div>
}
If i had to put what i wrote as an answer, you can go
public static string GetUserEmail(this HttpSessionState session)
{
if(Session["Email"] != null)
{
Session["email"] = ..Set Session email here
}
return session["Email"]
}
then you can either create a set session method or just use the Session["key"] to set the value, then you will have access to your email.
I am a beginner and learning ASP.Net MVC web development. I am stuck at one place.
I have a reset password window. If user successfully resets the password I want him to redirect to the same page but I want a "Password Reset Successful" message to be on top. It can be an alert or something. Just user should know that password has been reset. But I don't know how to achieve this. Below is what I have till now.
[HttpPost]
[ValidateAntiForgeryToken]
public ViewResult WidgetResetPassword(ResetPasswordMV data)
{
bool isValid = false;
isValid = ModelState.IsValid;
// verify the 2 password match
if (isValid && !data.NewPassword.Equals(data.ConfirmNewPassword))
{
isValid = false;
ModelState.AddModelError("ConfirmNewPassword", "Passwords doesn't match.");
}
if (isValid)
{
//setting the correct tenant id
if (Session[Constants.SESSION_USER_KEY] != null)
{
UserMV authenticatedUsers = (UserMV)Session[Constants.SESSION_USER_KEY];
data.UserId = authenticatedUsers.Id;
}
ResetPasswordHelper.Save(data);
}
return View(data);
}
My .cshtml file:
#model ResetPasswordMV
#using SIM_Obj.ModelViews;
#{
ViewBag.Title = "Reset Password";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#* <div id="ResetPasswordWidget" class="form-horizontal">*#
<div id="ResetPasswordWidget" class="form-horizontal-width-inherit">
<h3>Reset Password</h3>
<hr/>
#Html.ValidationSummary(true, "", new {#class = "text-danger"})
#Html.HiddenFor(model => model.UserId)
<div class="form-group">
#Html.LabelFor(model => model.OldPassword, htmlAttributes: new {#class = "control-label col-md-2"})
<div class="col-md-10">
#Html.EditorFor(model => model.OldPassword, new {htmlAttributes = new {#class = "form-control"}})
#Html.ValidationMessageFor(model => model.OldPassword, "", new {#class = "text-danger"})
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewPassword, htmlAttributes: new {#class = "control-label col-md-2"})
<div class="col-md-10">
#Html.EditorFor(model => model.NewPassword, new {htmlAttributes = new {#class = "form-control"}})
#Html.ValidationMessageFor(model => model.NewPassword, "", new {#class = "text-danger"})
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ConfirmNewPassword, htmlAttributes: new {#class = "control-label col-md-2"})
<div class="col-md-10">
#Html.EditorFor(model => model.ConfirmNewPassword, new {htmlAttributes = new {#class = "form-control"}})
#Html.ValidationMessageFor(model => model.ConfirmNewPassword, "", new {#class = "text-danger"})
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Reset Password" class="btn btn-default"/>
</div>
</div>
</div>
}
I want to be able to add something like:
<p class ="alert alert-success"> <strong>Success! </strong>Your Password has been successfully changed.</p>
Question 1: How to get this to be displayed when password is reset.
Question 2: Currently I am doing return view(data) in the controller. Is it necessary.
Question 3: Can I use something like partialview. I am beginner. Please guide me.
Add a property like ShowMessage to your model and set it if the reset was successful.
Change the view to
#if (model.ShowMessage)
{
<p class="alert alert-success"> <strong>Success! </strong>Your Password has been successfully changed.</p>
}
...
ViewBag.SaveResult=true;
return View(data);
.....
in view page
#if (ViewBag.SaveResult == true) {
<div class="alert alert-success" >
<strong>Success! </strong>Your Password has been successfully changed.</div>
}
I did this using ValidationMessage.
First in razor page add ValidationMessage for success and error:
#Html.ValidationMessage("ERROR", new { #class = "card-alert alert alert-danger v-message", #style = "display: none;" })
#Html.ValidationMessage("SUCCESS", new { #class = "card-alert alert alert-success v-message", #style = "display: none;" })
Then in controller you send error and success message using:
ModelState.AddModelError("SUCCESS", "Success message !");
ModelState.AddModelError("ERROR", "Error message !");
Add this code in JavaScript witch will display messages when needed:
$(".validation-message").each(function () {
if ($(this).text() !== "") {
$(this).css("display", "block");
}
});
I followed an online tutorial to dynamically add items to a bound list model using ajax, which works perfectly. (http://www.mattlunn.me.uk/blog/2014/08/how-to-dynamically-via-ajax-add-new-items-to-a-bound-list-model-in-asp-mvc-net/comment-page-2/#comment-68909)
My question is, how would I correctly remove items from the list?
Right now what I have done is add a delete link which when clicked removes the item from the view. However, when I submit the form I noticed that the modelState is no longer valid and it has null entries for the item that was removed from the view. So I guess the model is not being updated.
Test.cshtml
#model TesterManager.Models.Test
<div class="form-group">
#Html.LabelFor(model => model.Software, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="form-group">
<div class="col-md-5">
#Html.DropDownListFor(m => m.Software, TesterManager.Models.Helper.GetTestSoftwares(), "Choose a USB Card", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Software, "", new { #class = "text-danger" })
</div>
<div class="col-md-5">
#Html.EditorFor(model => model.Version, new { htmlAttributes = new { #class = "form-control", #title = "Enter a USB FW Version", #placeholder = "Enter a USB FW Version" } })
#Html.ValidationMessageFor(model => model.Version, "", new { #class = "text-danger" })
</div>
<div class="col-md-2">
Delete
</div>
</div>
</div>
</div>
AdminTesterConfigurations.cshtml (snippet):
#model TesterManager.Models.AdminTesterConfigurations
<div class="form-group">
<div class="col-md-6">
....
</div>
</div>
<hr />
<div class="form-group">
<div class="col-md-12">
<h3>Test Software</h3>
<div id="test-list">
#Html.EditorForMany(x => x.Tests, x => x.Index)
</div>
<input type="button" id="add-test" value="Add" />
</div>
</div>
RequestEditViewModel.cshtml:
#model TesterManager.Models.RequestEditViewModel
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.EditorFor(model => model.ShippingLocation)
#Html.EditorFor(model => model.RequesterTesterConfigurations)
#Html.EditorFor(model => model.AdminTesterConfigurations)
<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>
Edit.cshtml:
#model TesterManager.Models.RequestEditViewModel
#Styles.Render("~/Content/Edit")
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section Scripts
{
<script>
jQuery(document).ready(function ($) {
$('#add-test').on('click', function () {
jQuery.get('/TesterManager/Request/AddTest').done(function (html) {
$('#test-list').append(html);
});
});
});
</script>
}
#using (Html.BeginForm())
{
<h2>Edit</h2>
#Html.AntiForgeryToken()
#Html.EditorFor(x => x);
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
RequestController.cs
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(RequestEditViewModel request)
{
if (ModelState.IsValid)
{
Request domainRequest = new Request(request);
requests.Add(domainRequest);
return RedirectToAction("Index");
}
return View(request);
}
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult AddTest()
{
var request = new RequestEditViewModel();
request.AdminTesterConfigurations.Tests.Add(new Test());
return View(request);
}
I realized that the problem was that when I would remove the item from the list in the view, I was not removing the hidden input for the collection indexer as well. I updated the code to remove the hidden input and it works fine now.