This BankId field is required. When call the controller & execute that code always return false.
BankID data value entry one by one automatic & BankName data insert user input wise.
please any suggestion how to solve that problem in asp.net mvc razor
How to solve this problem. This BankId field is required.
When call the controller & execute that code always return false.
BankID data value entry one by one automatic & BankName data insert user input wise
Model Class: that section declare table filed
namespace gl.db
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
public partial class Bank
{
public Bank()
{
this.Branches = new HashSet<Branch>();
}
public int BankId { get; set; }n
[Required(ErrorMessage = "*")]
[Display(Name = "Bank")]
public string BankName { get; set; }
public virtual ICollection<Branch> Branches { get; set; }
}
}
Controller Code: declare how to insert into sql table
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult frmbank_create(FormCollection FrmCollection, [Bind(Include = "BankId, BankName")] Bank bank)
{
#ViewBag.Title = "Bank Information";
int i = -1;
if (FrmCollection["Refresh"] != null)
{
FrmClear();
return View();
}
else
{
if (ModelState.IsValid)
{
if (FrmCollection["Save"] != null)
{
i = objDBBank.Insert(bank);
}
else if (FrmCollection["Update"] != null)
{
i = objDBBank.Update(bank);
}
if (i > 0)
{
if (FrmCollection["Save"] != null)
{
ViewBag.Operation = "Insert";
ViewBag.Flag = "true";
}
else
{
ViewBag.Operation = "Update";
ViewBag.Flag = "true";
}
ModelState.Clear();
return View();
}
else
{
if (FrmCollection["Save"] != null)
{
ViewBag.Operation = "Insert";
ViewBag.Flag = "false";
}
else
{
ViewBag.Operation = "Update";
ViewBag.Flag = "false";
}
}
}
}
return View(bank);
}
View Code : declare css file view in browser
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="panel-body">
#Html.ValidationSummary(true)
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6">
<div class="form-inner12">
<div class="left-col">Bank</div>
<div class="right-col">
#Html.HiddenFor(model => model.BankId)
#Html.TextBoxFor(model => model.BankName, new { #class = "form-control in-ctrl" })
#Html.ValidationMessageFor(model => model.BankName)
</div>
<div class="clr"></div>
</div>
</div>
</div>
<div class="clr20"></div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<div class="form-inner12">
<div class="left-col"> </div>
<button type="submit" class="btn btn-primary #ViewBag.BtnBankSaveDis" name="Save" value="Save">Save</button>
<button type="submit" class="btn btn-primary #ViewBag.BtnBankUpdateDis" name="Update" value="Update">Update</button>
<button type="submit" class="btn btn-primary" name="Refresh" value="Refresh">Refresh</button>
<div class="clr"></div>
</div>
</div>
</div>
</div>
}
Int are not nullable thus making it always required without you putting data annotation. You could change your BankId to public int? BankId { get; set; }
Basically you should create different viewmodels for Create and Edit first that will solve your problem. you will not be having BankId in your Create viewmodel. that how the thing should go in asp.net mvc.
but in your scenario you could remove bankid from modelstate when creating the form before hitting model.IsValid
if (FrmCollection["Save"] != null)
{
ModelState.Remove("BankId");
}
Related
I have a form where users can upload files and then view a list of their uploads. I'm running into two issues:
List of files isn't appearing when page loads. The SQL Query is valid.
When user uploads a file, a NullReferenceException because the file list model isn't being loaded. I'm not sure how to pass this model into view after the upload. Any advice is greatly appreciated.
Controller for fetching list of datasets is below. The controller for uploading datasets is different, of course, but it accepts an HttpPostedFileBase and a datasetName. It only returns ViewBag.error/ViewBag.message.
public ActionResult upload(DatasetViewModel model)
{
List<DatasetDetail> model2 = new List<DatasetDetail>();
var connectionstring = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionstring))
try
{
// Your code
con.Open();
using (SqlCommand cmd = new SqlCommand("", con))
{
cmd.CommandText = "SELECT datasetid, datasetname, timestamp FROM datasets WHERE userid = #userid";
cmd.Parameters.Add("#userid", SqlDbType.Text);
cmd.Parameters["#userid"].Value = System.Web.HttpContext.Current.User.Identity.GetUserId();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
var u = new DatasetDetail();
u.datasetid = reader["datasetid"].ToString();
u.dataset = reader["datasetname"].ToString();
/* u.timestamp = Convert.ToDateTime(reader["TIMESTAMP"]);*/
model2.Add(u);
}
}
}
catch
{
// Catch exception
}
finally
{
// Close the connection
con.Close();
}
model.datasetlist = model2;
return View(model);
}
View:
#model WebApplication12.Models.DatasetViewModel
<div style="width: 320px;">
<h2>Manage Datasets</h2>
Download Excel Template
#using (Html.BeginForm("upload", "Dashboard", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<div class="form-group">
<label>Dataset Name:</label>
<br />
<input type="text" id="datasetname" name="datasetname" />
</div>
<div class="form-group">
<input type="file" id="dataFile" name="upload" />
</div>
<div class="form-group">
<input type="submit" value="submit" class="btn btn-block" />
</div>
}
</div>
<div id="response"></div>
#if (ViewBag.Message != null)
{
<div class="alert alert-success" role="alert">#Html.Raw(ViewBag.Message)</div>
}
#if (ViewBag.Error != null)
{
<div class="alert alert-error" role="alert">#Html.Raw(ViewBag.Error)</div>
}
<div>
#foreach (var u in Model.datasetlist)
{
<b>u.dataset</b>
}
</div>
Relevant Models:
public class DatasetViewModel
{
public List<DatasetDetail> datasetlist { get; set; }
}
public class DatasetDetail
{
public string datasetid { get; set; }
public string dataset { get; set; }
/* public DateTime timestamp { get; set; }*/
}
I am working on an ASP.NET MVC web application that uses Entity Framework.
Here is the model class:
public partial class Complaint
{
public int ComplaintId { get; set; }
public string Reference { get; set; }
public string ClientName { get; set; }
public string AccountNo { get; set; }
public Nullable<System.DateTime> DateComplaint { get; set; }
public Nullable<decimal> Value { get; set; }
public Nullable<int> TypeId { get; set; }
public string Comment { get; set; }
public Nullable<int> StatusId { get; set; }
public Nullable<System.Guid> InsertedBy { get; set; }
public Nullable<System.DateTime> CreatedDateTime { get; set; }
public Nullable<System.DateTime> ModifiedDateTime { get; set; }
public virtual ICollection<FileAttach> FileAttaches { get; set; }
}
Controller method:
[Authorize]
[AuthorizeRoles("Admin", "Oficial")]
public ActionResult RequestApproval(int? id)
{
ViewBag.Status = _context.Status.ToList();
//ViewBag.User = _context.Profiles.Where(x => x.User.UserRoles.FirstOrDefault().RoleId == 2 || x.User.UserRoles.FirstOrDefault().RoleId == 3).ToList();
if (id == 0)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Complaint c = _context.Complaints.Include(s => s.FileAttaches).SingleOrDefault(x => x.ComplaintId == id);
if (c == null)
{
return HttpNotFound();
}
return View(c);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RequestApproval(int? id, HttpPostedFileBase upload)
{
var c = _context.Complaints.Find(id);
if (TryUpdateModel(c, "", new string[] { "Reference", "ClientName", "AccountNo", "DateComplaint", "Value", "TypeId", "Comment", "StatusId", "IsApproved", "ApprovedBy", "InsertedBy", "UpdatedBy", "CreatedDateTime", "ModifiedDateTime" }))
{
for (int i = 0; i < Request.Files.Count; i++)
{
upload = Request.Files[i];
if (upload != null && upload.ContentLength > 0)
{
Stream str = upload.InputStream;
BinaryReader Br = new BinaryReader(str);
Byte[] FileDet = Br.ReadBytes((Int32)str.Length);
var fileName = Path.GetFileName(upload.FileName);
FileAttach fileDetail = new FileAttach()
{
Name = fileName,
ContentType = upload.ContentType,
Data = FileDet,
AttachId = new int(),
Path = Path.Combine(Server.MapPath("~/Uploads/"), fileName),
ComplaintId = id
};
var path = Path.Combine(Server.MapPath("~/Uploads/"), fileDetail.Name);
upload.SaveAs(path);
_context.Entry(fileDetail).State = EntityState.Added;
}
}
_context.Entry(c).State = EntityState.Modified;
_context.SaveChanges();
return RedirectToAction("List");
}
return View(c);
}
My view:
<div data-parsley-validate class="form-horizontal form-label-left">
#using (Html.BeginForm("RequestApproval", "Complaint", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.ComplaintId, new { #class = "id" })
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="first-name">
#Html.LabelFor(model => model.Reference) <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
#Html.DropDownListFor(model => model.StatusId, new SelectList(ViewBag.Status, "StatusId", "Denomination"), "- Please select a type -",
new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="first-name">
#Html.LabelFor(model => model.Comment) <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
#Html.TextAreaFor(model => model.Comment, new { #class = "form-control col-md-7 col-xs-12", style = "width:100% auto; height:150px;" })
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="first-name">
Files
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input type="file" name="file" id="fileUpload" multiple="multiple" />
<ul class="attachment">
#foreach (var item in Model.FileAttaches)
{
<li>
<a class="title" href="/Complaint/Download/?p=#(item.Name)&d=#item.Name">#item.Name</a>
</li>
}
</ul>
</div>
</div>
<div class="ln_solid"></div>
<div class="form-group">
<div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3">
<button type="submit" class="btn btn-primary btn-sm">Back To List</button>
<button type="submit" class="btn btn-success btn-sm">Save <i class="fa fa-save"></i></button>
</div>
</div>
}
</div>
When I try to edit I get this error:
Server Error in '/' Application
Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: model
enter image description here
New to web development.
I have a view that allows user to select an excel file.
When submit "preview" button is pressed file is read and data is sent back to the user to preview the data.
Then I want to be able send the model back to the control for db upload.
(this is the part I'm struggling with).
ViewModel:
public class UploadItemsViewModel
{
public List<Item> Items { get; set; }
public int CompanyID { get; set; }
public Company Company { get; set; }
public HttpPostedFileBase upload { get; set; }
public UploadJournalsViewModel()
{
Items = new List<Item>();
}
}
Controller:
public ActionResult Upload(FormCollection formCollection, int CompanyID)
{
if (Request != null)
{
HttpPostedFileBase file = Request.Files["UploadedFile"];
if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
{
string fileName = file.FileName;
string fileContentType = file.ContentType;
byte[] fileBytes = new byte[file.ContentLength];
var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
}
}
UploadItemsViewModel itmViewModel = new UploadItemsViewModel { Company = db.Companies.Find(CompanyID), CompanyID = CompanyID };
return View(itmViewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(UploadItemsViewModel itmViewModel, string Preview, string Upload)
{
if (ModelState.IsValid)
{
if (itmViewModel.upload != null && itmViewModel.upload.ContentLength >0)
{
try
{
itmlViewModel.Items = App.Services.ItemsMassUploadFileRead.ReadExcelFile(itmViewModel.upload, db.Companies.Find(itmViewModel.CompanyID));
if (string.IsNullOrEmpty(Preview))
{
foreach (var itm in itmViewModel.Items)
{
itm.StartDate = DateTime.Today;
itm.CompanyID = itmViewModel.CompanyID;
itm.User = null;
itm.Items.Add(itm);
db.SaveChanges();
}
return View();
}
else
{
return View(itmViewModel);
}
} }
catch (Exception ex)
{
ModelState.AddModelError("File", ex.Message.ToString());
return View(itmViewModel);
}
}
else
{
ModelState.AddModelError("File", "Please Upload Your file");
}
}
return View(itmViewModel);
}
View:
#using (Html.BeginForm("Upload", "ItemsUpload", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.CompanyID)
<div class="form-group">
<div class="input-group">
<label class="input-group-btn">
<span class="btn btn-default">
Browse… <input type="file" style="display: none;" accept=".xlsx" name="upload">
</span>
</label>
<input type="text" class="form-control " readonly>
</div>
<span class="help-block">
Please use a provided Excel template
</span>
</div>
<div class="form-group">
<input type="submit" value="Preview" name ="Preview" class="btn btn-default" disabled style="display: none" id="submit"/>
</div>
<div class="form-group">
<input type="submit" value="Upload" name="Upload" class="btn btn-default" id="Upload" />
</div>
<div class="help-block" id="previewHelp" style="display: none">
Preview results and scroll down to upload data to the database.
</div>
if (Model.Journals.Count != 0)
{
table here to preview the upload
}
After clicking the Upload button model comes back without the "items" collection.
The Items list will be always null in the controller, because you don't rendered any input on the View with the name Items
I'm working on a small "Rent-a-car" application. I have a list of Cars that client can see and i want to implement "Order feature" on that list. Every car should have order button on his side. When the client chooses car and presses button "Order" i want to have opened Bootstrap Modal that says something like "You want to order car that client selected , please enter your personal information". Then he will enter his name, email, and phone number. When he enters that he will press "Submit" button on that modal and he will get message something like "We sent a payment link and instruction for paying on your email. Please check your email." Then the client will get email that will say "You want to order car that the client selected . Please read following instructions: Some text"
I suppose i can do this with Action Links but i don't know how to implement it in my existing code
Please note: This doesn't have to be made using Bootstrap Modals. I am opened for your suggestions. Please review my existing code.
This is my Car model:
public class Car
{
[Key]
public int CarID { get; set; }
public string Model { get; set; }
[DisplayName("Year of production")]
public int YearOfProduction { get; set; }
public string Price { get; set; }
public virtual ICollection<FilePath> FilePaths { get; set; }
[DisplayName("Air Conditioning")]
public string AirConditioning { get; set; }
[DisplayName("Engine")]
public string EngineType { get; set; }
public string Transmission { get; set; }
public string Suitcases { get; set; }
public string Seats { get; set; }
}
This is my Cars controller:
public class CarsController : Controller
{
private CarContext db = new CarContext();
// GET: Cars
public ActionResult Index()
{
return View(db.Cars.ToList());
}
// GET: Cars/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//Car car = db.Cars.Find(id);
Car car = db.Cars.Include(i => i.FilePaths).SingleOrDefault(i => i.CarID == id);
if (car == null)
{
return HttpNotFound();
}
return View(car);
}
// GET: Cars/Create
[Authorize(Roles = "Administrator")]
public ActionResult Create()
{
return View();
}
// POST: Cars/Create
[Authorize(Roles = "Administrator")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "CarID,Model,YearOfProduction,Price,AirConditioning,EngineType,Transmission, Suitcases, Seats")] Car car, HttpPostedFileBase upload)
{
if (ModelState.IsValid)
{
if (upload != null && upload.ContentLength > 0)
{
var photo = new FilePath
{
FileName = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(upload.FileName), //uniqueness of the file name
FileType = FileType.Photo
};
car.FilePaths = new List<FilePath>();
upload.SaveAs(Path.Combine(Server.MapPath("~/Images/Cars"), photo.FileName));
car.FilePaths.Add(photo);
}
db.Cars.Add(car);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(car);
}
// GET: Cars/Edit/5
[Authorize(Roles = "Administrator")]
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Car car = db.Cars.Find(id);
if (car == null)
{
return HttpNotFound();
}
return View(car);
}
[Authorize(Roles = "Administrator")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "CarID,Model,YearOfProduction,Price,AirConditioning,EngineType,Transmission, Suitcases, Seats")] Car car, HttpPostedFileBase upload)
{
if (ModelState.IsValid)
{
if (upload != null && upload.ContentLength > 0)
{
var photo = new FilePath
{
FileName = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(upload.FileName), //uniqueness of the file name
FileType = FileType.Photo
};
car.FilePaths = new List<FilePath>();
upload.SaveAs(Path.Combine(Server.MapPath("~/Images/Cars"), photo.FileName));
car.FilePaths.Add(photo);
}
db.Cars.Add(car);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(car);
}
// GET: Cars/Delete/5
[Authorize(Roles = "Administrator")]
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Car car = db.Cars.Find(id);
if (car == null)
{
return HttpNotFound();
}
return View(car);
}
// POST: Cars/Delete/5
[Authorize(Roles = "Administrator")]
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Car car = db.Cars.Find(id);
db.Cars.Remove(car);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
This is my Index view of the Cars controller where i put list of the cars and modals for ordering:
#model IEnumerable<Testing_identity_2.Models.Car>
#{
ViewBag.Title = "Index";
}
<h2>AVAILABLE CARS</h2>
#if (ViewContext.HttpContext.User.IsInRole("Administrator"))
{
<p>
#Html.ActionLink("Create New", "Create")
</p>
}
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Model)
</th>
<th>
#Html.DisplayNameFor(model => model.Price)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td class="col-md-3">
#Html.DisplayFor(modelItem => item.Model)
</td>
<td class="col-md-2">
#Html.DisplayFor(modelItem => item.Price)
</td>
<td>
<button class="btn btn-default btn-sm" data-target="#orderModal" data-toggle="modal">Order</button>
#Html.ActionLink("Details", "Details", new {id = item.CarID}, new {#class = "btn btn-default btn-sm"})
#if (ViewContext.HttpContext.User.IsInRole("Administrator"))
{
#Html.ActionLink("Edit", "Edit", new {id = item.CarID}, new {#class = "btn btn-default btn-sm"})
}
#if (ViewContext.HttpContext.User.IsInRole("Administrator"))
{
#Html.ActionLink("Delete", "Delete", new {id = item.CarID}, new {#class = "btn btn-default btn-sm"})
}
</td>
</tr>
}
</table>
<div class="modal" data-keyboard="false" data-backdrop="static" id="orderModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Please enter your personal information</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="inputName">Name</label>
<input class="form-control" placeholder="Name" type="text" id="inputName" />
</div>
<div class="form-group">
<label for="inputEmail">Email</label>
<input class="form-control" placeholder="Email" type="text" id="inputEmail" />
</div>
<div class="form-group">
<label for="inputPhoneNumber">Phone Number</label>
<input class="form-control" placeholder="Phone Number" type="text" id="inputPhoneNumber" />
</div>
</form>
</div>
<div class="modal-footer">
<button id="btnSubmitModal" class="btn btn-primary">Submit</button>
<button class="btn btn-primary" id="btnHideModal2">Close</button>
</div>
</div>
</div>
</div>
<div class="modal" data-keyboard="false" data-backdrop="static" id="orderModal1" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
</div>
<div class="modal-body">
<form>
<h4 class="modal-title">We sent a payment link on your email.</h4>
<br />
<h4 class="modal-title">Please check your email.</h4>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary" id="btnHideModal1">Close</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#btnSubmitModal').click(function () {
$('#orderModal').modal('hide');
});
$('#orderModal').on('hide.bs.modal', function (){
$('#orderModal1').modal('show');
});
$('#btnHideModal1').click(function () {
$('#orderModal1').modal('hide');
});
$('#btnHideModal2').click(function () {
$('#orderModal').modal('hide');
$('#orderModal1').modal('hide');
});
});
</script>
There are several things that you are asking for. First, You need to add an actionlink tag with a binding id in your #foreach loop, for example:
#Html.Actionlink("Order car here!", "Order", new { id=item.CarID })
With the controller actionresult looking similar to this:
Public ActionResult Order(int id)
{
return View("Order");
}
Second, you want to have an order page in which the user can enter their data, using razor or angularJS. I recommend that you have a separate model for storing user data:
class client
{
public int userID { get; set; }
public string email { get; set; }
public string Name { get; set; }
public int PhoneNumber { get; set; }
}
An example Order page:
<div>
<div>
#Html.Label("emailaddress","Email address")
#Html.Editor("Email")
</div>
<div>
#Html.Label("NameLabel", "First Name")
#Html.Editor("Name")
</div>
<div>
#Html.Label("PhoneNumberLabel", "Phone Number")
#Html.Editor("PhoneNumber")
</div>
#Html.ActionLink("Submit order form", "submitOrder", new { email=Model.email, name=Model.name, PhoneNumber=Model.PhoneNumber})
</div>
PLEASE NOTE: The order form is a rough outline and will need some work to submit the forms data. The form will then submit this data to another ActionResult that will utilise the SMTP namespace(System.Net.Mail):
public ActionResult subOrder(string email, string name,
{
MailMessage mail = new MailMessage("exampleNoReponseEmail#emailexample.com", email);
SmtpClient client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Host = "smtp.google.com";
mail.Subject = "Car payment conformation";
mail.Subject = "Dear, " + name + ", "You want to order car that the client selected . Please read following instructions: Some text";
client.Send(mail);
return View("ConfirmPayment");
}
The confirm email view:
<h1>Email Sent!</h1>
<p>We sent a payment link and instruction for paying on your email. Please check your email.</p>
These links about sending email might also help:
1. Send e-mail via SMTP using C#
2. Sending email in .NET through Gmail
3. https://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage(v=vs.110).aspx
4. https://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient(v=vs.110).aspx
I hope this helps!
I have read plenty of posts about this issue but I can't seem to find a solution that fits with my implementation. I'm giving MVC another attempt (I'm a webforms guy). The model being passed to my ActionResult is basically empty when it should be populated. I'm starring at the sample that works and I can find no differences. It seems to be something impossible to debug too. Any pointers will be greatfully appreciated.
View:
#model WebApplication1.Models.SiteViewModel
#{
ViewBag.Title = "Delete your site";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<p>Are you sure you want to delete this site?</p>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(false)
<ul class="list-group">
<li class="list-group-item">
<div class="row">
<div class="col-md-2"><b>#Html.LabelFor(model => model.Name)</b></div>
<div class="col-md-6">#Model.Name</div>
</div>
</li>
<li class="list-group-item">
<div class="row">
<div class="col-md-2"><b>#Html.LabelFor(model => model.Phase)</b></div>
<div class="col-md-6">#Model.Phase</div>
</div>
</li>
<li class="list-group-item">
<div class="row">
<div class="col-md-2"><b>#Html.LabelFor(model => model.Type)</b></div>
<div class="col-md-6">#Model.Type</div>
</div>
</li>
</ul>
<button type="submit" class="btn btn-danger">Delete</button>
#Html.ActionLink("Back to List", "Index", null, new { #class = "btn btn-default" })
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Model:
public class SiteViewModel
{
public SiteViewModel()
{
Services = new List<ServiceModel>();
}
public SiteViewModel(SiteModel site)
{
this.SiteId = site.SiteId;
this.Name = site.Name;
this.Type = site.Type;
this.Phase = site.Phase;
this.Services = site.Services;
}
public int SiteId { get; set; }
[Required(ErrorMessage = "Name is required")]
public string Name { get; set; }
public SchoolType Type { get; set; }
public SchoolPhase Phase { get; set; }
public DateTime? Deleted { get; set; }
public virtual ICollection<ServiceModel> Services { get; set; }
}
Controller Action:
[HttpPost]
public ActionResult Delete(SiteViewModel model)
{
var site = siteRepository.GetById(model.SiteId);
if (site == null) { throw new ArgumentException(string.Format("Site with Id [{0}] does not exist", model.SiteId)); }
try
{
siteRepository.SoftDeleteAndSubmit(site);
base.SetSuccessMessage("The site has been (soft) deleted.");
return RedirectToAction("Index");
}
catch (Exception ex)
{
base.SetErrorMessage("Whoops! Couldn't delete the site. The error was [{0}]", ex.Message);
}
return View(model);
}
Thanks,
Chris.
If you want a fully-populated model you'll need to use form elements or the form helper functions to post your data.
#using(Html.BeginForm())
{
<input type="text" value="#Model.Name" />
// or
Html.TextBoxFor(m => m.Name)
...
}
The example you linked relies on a URL routing rule to match a model's parameter. So you need to rename SiteId to Id or add/modify a routing rule.
If you only need the id then I would just pass that parameter as it will make your intent more obvious and is less prone to breaking.
#using(Html.BeginForm())
{
#Html.HiddenFor(m => m.Id)
<button type="submit">Delete</button>
}
[HttpPost]
public ActionResult Delete(int id)
{
var site = siteRepository.GetById(id);
...
}