I am currently using a template in order to create a website. In the contact page I want to create a form where the user will be able to contact the company from a contact us template. The template comes with a contact_us.php file but I want to use only asp.net for the emails.
I am a beginner and I am not really sure how the controllers works in asp.net.
Heres my code:
View: Contact.cshtml
#model Gsite.Models.ContactUs
#{
Layout = "~/Views/Shared/_CustomLayout.cshtml";
}
<script src="~/Content/vendor/jquery/jquery.js"></script>
<script src="~/Content/vendor/jquery/jquery.min.js"></script>
<!-- Contact Form -->
<!-- In order to set the email address and subject line for the contact form go to the bin/contact_me.php file. -->
<div class="row">
<div class="col-lg-8 mb-4">
<h3>Send us a Message</h3>
#if (ViewBag.Message == null)
{
<form method ="post" name="sentMessage" id="contactForm" novalidate>
<div class="control-group form-group">
<div class="controls">
<label asp-for="Name">Full Name:</label>
<input asp-for="Name" type="text" class="form-control" id="name" required data-validation-required-message="Please enter your name.">
<span asp-validation-for="Name"
class="text-muted"></span>
<p class="help-block"></p>
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label asp-for="phonenumber">Phone Number:</label>
<input asp-for="phonenumber" type="tel" class="form-control" id="phone" required data-validation-required-message="Please enter your phone number.">
<span asp-validation-for="phonenumber"
class="text-muted"></span>
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label asp-for="Email">Email Address:</label>
<input asp-for="Email" type="email" class="form-control" id="email" required data-validation-required-message="Please enter your email address.">
<span asp-validation-for="Email"
class="text-muted"></span>
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label asp-for="Message">Message:</label>
<textarea asp-for="Message" rows="10" cols="100" class="form-control" id="message" required data-validation-required-message="Please enter your message" maxlength="999" style="resize:none"></textarea>
<span asp-validation-for="Message"
class="text-muted"></span>
</div>
</div>
<div id="success"></div>
<!-- For success/fail messages -->
<button type="submit" class="btn btn-primary" id="sendMessageButton">Send Message</button>
</form>
}
</div>
</div>
<!-- /.row -->
<div>
<div>
#if (ViewBag.Message != null)
{
<div>#ViewBag.Message</div>
}
</div>
</div>
</div>
<script src="~/Content/vendor/jquery/jquery.min.js"></script>
<script src="~/Scripts/jqBootstrapValidation.js"></script>
<script src="~/Scripts/contact_me.js"></script>
Controller: ContactController
namespace Gsite.Controllers
{
public class ContactController : Controller
{
// GET: Contact
public ActionResult Contact()
{
return View();
}
[HttpPost]
public ActionResult Contact(ContactUs vm)
{
if (ModelState.IsValid)
{
try
{
MailMessage msz = new MailMessage();
msz.From = new MailAddress(vm.Email);//Email which you are getting
//from contact us page
msz.To.Add("xxx#xxx.com");//Where mail will be sent
msz.Body = vm.Message;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.Credentials = new System.Net.NetworkCredential
("xxxxx#xxxxx.com", "xxxxx");
smtp.EnableSsl = true;
smtp.Send(msz);
ModelState.Clear();
ViewBag.Message = "Thank you for Contacting us ";
}
catch (Exception ex)
{
ModelState.Clear();
ViewBag.Message = $" Sorry we are facing Problem here {ex.Message}";
}
}
return View();
}
public ActionResult Error()
{
return View();
}
}
}
Model: ContactUs.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Gsite.Models
{
public class ContactUs
{
[Required]
[StringLength(20, MinimumLength = 5)]
public string Name { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
public string Message { get; set; }
[Required]
public int phonenumber { get; set; }
}
}
This will work in an Asp.net MVC application. Does the application has got both Asp.net MVC and Php codes? Assuming 'yes', you need to set the action property of the form element.
e.g. <form action="/Contact/Contact">
Also set the "name" property of the input boxes to match the properties of the ContactUs object.
Related
I've got number of places where I need to use an address in my app so I tried to make this DRY and create an address partial view like this:
#model AddressEditViewModel
<div class="mb-3">
<label asp-for="Address1" class="form-label"></label>
<input asp-for="Address1" class="form-control" />
<span asp-validation-for="Address1" class="text-danger"></span>
</div>
<div class="mb-3">
<label asp-for="Address2" class="form-label"></label>
<input asp-for="Address2" class="form-control" />
<span asp-validation-for="Address2" class="text-danger"></span>
</div>
<div class="mb-3">
<label asp-for="City" class="form-label"></label>
<input asp-for="City" class="form-control" />
<span asp-validation-for="City" class="text-danger"></span>
</div>
<div class="row mb-3">
<div class="col-md">
<label asp-for="USStateID" class="form-label"></label>
<select asp-items="#Model.USStates" asp-for="USStateID" class="form-select"></select>
<span asp-validation-for="USStateID" class="text-danger"></span>
</div>
<div class="col-md">
<label asp-for="Zip" class="form-label"></label>
<input asp-for="Zip" class="form-control" />
<span asp-validation-for="Zip" class="text-danger"></span>
</div>
</div>
But I had no luck when I put it into another page with the partial tag helper:
<partial name="_Address" model="Model.Address" />
Now I understand why this technique doesn't work - that partial views are just for making HTML and don't get processed by the model binder on the way back.
But I would prefer not to copy and paste forms all over my site. Is there any better way to reuse commonly used form bits like this?
You can use this method.
#await Html.PartialAsync("_PartialName", customViewData)
You can find more details in here.
https://learn.microsoft.com/en-us/aspnet/core/mvc/views/partial?view=aspnetcore-7.0#access-data-from-partial-views
You need to make sure the type of Model.Address is AddressEditViewModel.And make sure the partial view is in the right folder so that you can call it.
Model:
public class TestModel {
public AddressEditViewModel Address { get; set; }
}
public class AddressEditViewModel {
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public int USStateID { get; set; }
public List<SelectListItem> USStates { get; set; }
public string Zip { get; set; }
}
Action:
public IActionResult B()
{
return View(new TestModel {Address=new AddressEditViewModel { Address1="d1",Address2="d2", City="C", USStates=new List<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem> { }, Zip="111"} });
}
_Address.cshtml path:
Views/Shared/_Address.cshtml
B.cshtml:
#model TestModel
<partial name="_Address" model="Model.Address" />
result:
I can't understand why the data is not transferred to the database
There is a controller
public class PeopleController : Controller
{
private readonly string ConnectionString = "Host=localhost;Port=5432;Database=CrudDb;Username=postgres;Password=12345;Maximum Pool Size=100";
[HttpGet]
public IActionResult Create()
{
return View();
}
[HttpPost]
public IActionResult Create(People people)
{
if (ModelState.IsValid)
{
IDbConnection con;
string insertQuery = "INSERT INTO people(name, phone) VALUES(#Name, #Phone)";
con = new NpgsqlConnection(ConnectionString);
con.Open();
con.Execute(insertQuery, people);
con.Close();
return RedirectToAction(nameof(Index));
}
return View(people);
}
}
There is a model for her
public class People
{
public int Id { get; set; }
public string Name { get; set; }
public int Phone { get; set; }
}
And there is a page
<form asp-action="Contacts">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="col-form-label">Имя</label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Phone" class="col-form-label">Телефон </label>
<input asp-for="Phone" class="form-control" />
<span asp-validation-for="Phone" class="text-danger"></span>
</div>
<div class="form-group p-4">
<input type="submit" value="Создать" class="btn btn-outline-success btn-sm" />
</div>
</form>
It does not issue any errors, I enter data on the page, but this data is not transmitted to the database. From libraries, Dapper and Npgsql are connected
I am trying to make a validation for my report form where the report can only be submited if the email = to "Sample#email.com". My problem is the code works perfectly without the validation but when I include the validation code if (!ModelState.IsValid){return View("Create");} into the my controller the validation works perfectly but when the email is correct it just refreshes the page without submiting it or redirecting it to the submit view
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Submit(Reports report)
{
if (!ModelState.IsValid)
{
return View("Create");
}
_reportRepository.CreateReport(report);
return View();
Validation Code:
public class EmailValidation : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var report = (Reports)validationContext.ObjectInstance;
if (report.Email == "Sample#email.com")
{
return ValidationResult.Success;
}
return new ValidationResult("Invalid email");
}
}
Report:
public class Reports
{
[Key]
public int ReportId { get; set; }
[Required(ErrorMessage = "Please enter email.")]
[Display(Name = "Email :")]
[EmailValidation(ErrorMessage ="enter valid email")]
public string Email { get; set; }
}
Create View:
#model Reports
#using Microsoft.AspNetCore.Identity
#inject UserManager<IdentityUser> UserManager
<body>
<form asp-action="Submit" method="post" role="form">
<div class="container1">
<div class=" form-group row">
<label asp-for="Email" class="col-md-2 control-label"></label>
<div class="col-md-3">
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
</div>
<div class="form-group row float-right">
<div class="col-md-offset-2 col-md-5 float-md-left">
<input type="submit" class="btn btn-primary" value="Submit" />
</div>
</div>
When I am making a WebAPI call I want to find out how to pass back ModelState errors to my Blazor application.
The DataAnnotations all validate correctly but, if I do any other types of validation (once past the ModelState.IsValid call), I can't get those errors that I add to the ModelState to pass back to Blazor. What am I missing?
Blazor page
...
<EditForm Model="#_user" OnValidSubmit="#Update">
<DataAnnotationsValidator />
<ValidationSummary />
<div class="container">
<div class="row">
<div class="col-md-3">Name:</div>
<div class="col-md-9"><InputText id="Name" #bind-Value="#_user.UserName" class="form-control" /></div>
</div>
#if (_user.isNew)
{
<div class="row">
<div class="col-md-3">Password:</div>
<div class="col-md-9"><InputText id="Name" #bind-Value="#_user.Password" class="form-control" type="password" /></div>
</div>
<div class="row">
<div class="col-md-3">Validate your password:</div>
<div class="col-md-9"><InputText id="Name" #bind-Value="#_user.ValidatePassword" class="form-control" type="password" /></div>
</div>
}
<div class="row">
<div class="col-md-3">Email:</div>
<div class="col-md-9"><InputText id="Name" #bind-Value="#_user.Email" class="form-control" /></div>
</div>
<div class="row">
<div class="col-md-3">Roles:</div>
<div class="col-md-9">
#foreach (IdentityRole role in _roles)
{
bool isChecked = _user.UserRoles.Any(r => r.Id == role.Id);
<input type="checkbox" Id="#role.Id" name="#role.Id"
Class="form-control" checked="#isChecked" #onchange="#(e => RoleChecked(e, role.Id))" />
#role.Name
}
</div>
</div>
<button type="submit" class="btn btn-#buttonClass">#buttonText</button>
</div>
</EditForm>
}
#functions {
[Parameter]
string id { get; set; } = "";
private UserViewModel _user { get; set; }
...
private async Task Update()
{
if (id != "")
{
await apiClient.UpdateUserAsync(_user);
}
else
{
await apiClient.AddUserAsync(_user);
}
UriHelper.NavigateTo("admin/users");
}
...
WebAPI Controller
[HttpPost]
public async Task<IActionResult> Post([FromBody] UserViewModel applicationUser)
{
if (applicationUser == null)
{
_logger.LogError($"ApplicationUser object null");
return BadRequest("ApplicationUser object is null");
}
if (!ModelState.IsValid)
{
_logger.LogWarn("ApplicationUser object invalid");
return BadRequest(ModelState);
}
else
{
_logger.LogDebug($"Creating ApplicationUser {applicationUser.UserName}");
var obj = new ApplicationUser();
obj.Map(applicationUser);
IdentityResult result = await _userManager.CreateAsync(obj, applicationUser.Password);
if (result.Succeeded)
{
//put the newly created user back on top of the parameter for role creation
applicationUser.Map(obj);
await IdentityHelpers.UpdateUserRoles(_userManager, applicationUser);
return CreatedAtRoute("", new { id = applicationUser.Id }, applicationUser);
}
else
{
_logger.LogWarn("ApplicationUser object could not be created");
result.Errors.ToList().ForEach(e => ModelState.AddModelError(e.Code, e.Description));
return BadRequest(ModelState);
}
}
}
How do I pass back ModelState errors to Blazor so that it will respond to those in the same way that it would DataAnnotations (or model validation)?
I'm using ASP.NET MVC framework and RavenDB to develop a website for restaurants to take reservations and orders online.
In the admin site, the admin is able to add restaurant. After restaurant is added, the admin can click 'Add Menu' to navigate to the add menu page (as shown below)
However, when the menu is added, the restaurant name is not being saved to the DB.
In RavenDB,
{
"foodItemCode": "A01",
"foodItemName": "Butter & Spice Chicken Chop",
"price": 16,
"description": null
}
How can I pass the restaurant name clicked from the restaurantList while saving the data of menu to DB?
Sorry if this question sounds dumb to anyone but I'm need a beginner so please bear with me while I am putting effort to learn more :)
EDIT
RestaurantMenu.cs - model for AddMenu.cshtml
public class RestaurantMenu
{
public string restaurantName { get; set; }
public string foodItemCode { get; set; }
public string foodItemName { get; set; }
public decimal price { get; set; }
public string description { get; set; }
}
AddMenu.cshtml
#model Foodfury.Models.Restaurant
<div class="addMenu">
#using (Html.BeginForm("AddMenu", "Admin", method: FormMethod.Post, htmlAttributes: new { #class = "ui form" }))
{
<div class="field">
<label>Restaurant</label>
<input type="text" name="model.restaurantName" value="#Html.DisplayFor(model => model.RestaurantName)" />
</div>
<div class="field">
<label>Food code (Optional)</label>
<input class="ui input" type="text" name="model.foodItemCode" />
</div>
<div class="field">
<label>Food Name</label>
<input class="ui input" type="text" name="model.foodItemName" />
</div>
<div class="field">
<label>Description</label>
<input class="ui input" type="text" name="model.description" />
</div>
<div class="field">
<label>Price</label>
<input class="ui input" type="number" name="model.price" />
</div>
<div class="ui buttons">
<button class="ui button">Cancel</button>
<div class="or"></div>
<button class="ui positive button" type="submit" id="btnAddMenu">Add to menu</button>
</div>
}
</div>
I'm not sure what am I doing wrong in order to pass the restaurant name clicked when inserting new menu.
In my controller,
[HttpPost]
public ActionResult AddMenu(RestaurantMenu model)
{
using (var store = new DocumentStore
{
Url = "http://localhost:8080/",
DefaultDatabase = "foodfurydb"
})
{
store.Initialize();
using (var session = store.OpenSession())
{
session.Store(model);
session.SaveChanges();
}
}
return View();
}