asp.net mvc 4 letter from site add attachment - asp.net-mvc

I have feedback form on my site, it looks like
I created model for my form
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace CorePartners_Site2.Models
{
public class FeedbackForm
{
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Company { get; set; }
public string AdditionalInformation { get; set; }
[FileExtensions(Extensions = "doc,txt,pdf")]
public HttpPostedFileBase ProjectInformation { get; set; }
}
}
and created view
#using (Html.BeginForm("Feedback", "Home", FormMethod.Post, new { id = "feedback-form" }))
{
#Html.TextBoxFor(model => model.Name, null, new { #class = "text-field" })
#Html.TextBoxFor(model => model.Email, null, new { #class = "text-field" })
#Html.TextBoxFor(model => model.Phone, null, new { #class = "text-field" })
#Html.TextBoxFor(model => model.Company, null, new { #class = "text-field" })
#Html.TextAreaFor(model => model.AdditionalInformation, new { cols="1", rows="1" })
#Html.TextBoxFor(model => model.ProjectInformation, null, new { type="file", #class="input-file" })
<em><b>Send</b></em>
}
I'd like to know will my form work with a for submit instead <input type="submit" /> ?
And I dont know how to make attachment to letter,
I tried to make
[HttpGet]
public ActionResult Feedback()
{
return View();
}
[HttpPost]
public ActionResult Feedback(FeedbackForm Model)
{
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.BodyEncoding = Encoding.UTF8;
msg.From = new MailAddress(Model.Email, #Resources.Global.Feedback_Email_Title);
msg.To.Add("tayna-anita#mail.ru");
string message = #Resources.Global.Feedback_Name + ": " + Model.Name + "\n"
+ #Resources.Global.Feedback_Email + ": " + Model.Email + "\n"
+ #Resources.Global.Feedback_Phone + ": " + Model.Phone + "\n"
+ #Resources.Global.Feedback_Company + ": " + Model.Company + "\n\n"
+ Model.AdditionalInformation;
msg.Body = message;
msg.IsBodyHtml = false;
//Attachment
if (Model.ProjectInformation != null)
{
HttpPostedFileBase attFile = Model.ProjectInformation;
int attachFileLength = attFile.ContentLength;
if (attachFileLength > 0)
{
string strFileName = Path.GetFileName(Model.ProjectInformation.FileName);
Model.ProjectInformation.SaveAs(Server.MapPath(strFileName));
MailAttachment attach = new MailAttachment(Server.MapPath(strFileName));
msg.Attachments.Add(attach);
string attach1 = strFileName;
}
}
SmtpClient client = new SmtpClient("smtp.mail.ru", 25);
client.UseDefaultCredentials = false;
client.EnableSsl = false;
try
{
client.Send(msg);
}
catch (Exception ex)
{
}
FeedbackForm tempForm = new FeedbackForm();
return View(tempForm);
}
but it shows a mistake in msg.Attachments.Add(attach); and it seems it will not work.

Well to answer your first question yes you can use an anchor tag in place of a submit input.
You will want to disable the tags default behaviour with javascript/jquery like this and then have it submit the form:
$(function () {
$('a.something').on("click", function (e) {
e.preventDefault();
$('feedback-form').submit();
});
});
The error you are receiving is because you are using the wrong object type for the msg.attachments.add() method. You need to use an Attachment object not a MailAttachment object.
Something like this:
Stream attachmentStream = File.OpenRead (file);
streams.Add (attachmentStream);
mail.Attachments.Add (new Attachment (attachmentStream, Path.GetFileName (file));

Related

Validation Error without posting data in MVC

I am using same form for Inserting new records and updating existing records. But, issue is that validation on all controls are shown as soon as form is loaded i.e. it should display validation message summary once this does not match criteria. I want to avoid validation message summary before clicking on submit button.
Controller:
using CRUD_logudTycoon_Revision_3.Context;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CRUD_logudTycoon_Revision_3.Controllers
{
public class HomeController : Controller
{
// GET: Home
testEntities dbContext = new testEntities();
public ActionResult HomePage()
{
return View();
}
public ActionResult Student(tbl_Student obj)
{
if (obj != null)
{
return View(obj);
}
return View("Student");
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult AddStudent(tbl_Student stu)
{
if (ModelState.IsValid)
{
tbl_Student res = new tbl_Student();
res.ID = stu.ID;
res.Name = stu.Name;
res.Fname = stu.Fname;
res.Email = stu.Email;
res.Mobile = stu.Mobile;
res.Description = stu.Description;
if (stu.ID == 0)
{
dbContext.tbl_Student.Add(res);
dbContext.SaveChanges();
}
else
{
dbContext.Entry(res).State = System.Data.Entity.EntityState.Modified;
dbContext.SaveChanges();
}
}
ModelState.Clear();
//return View("Student");
return RedirectToAction("StudentList");
}
public ActionResult StudentList()
{
var result = dbContext.tbl_Student.ToList();
return View(result);
}
public ActionResult Delete(int ID)
{
var result = dbContext.tbl_Student.Where(x => x.ID == ID).First();
dbContext.tbl_Student.Remove(result);
dbContext.SaveChanges();
var newlist = dbContext.tbl_Student.ToList();
return View("StudentList", newlist);
}
}
}
Student Action (Insert/Edit):
#model CRUD_logudTycoon_Revision_3.Context.tbl_Student
#{
ViewBag.Title = "Student";
}
<style>
.error {
color: red;
}
</style>
<h2>Student Registration Page</h2>
#using (Html.BeginForm("AddStudent", "Home", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="container">
<div class="form-group">
#Html.HiddenFor(x => x.ID)
#Html.Label("Student Name")
#Html.ValidationMessageFor(x => x.Name, "", new { #class = "error" })
#Html.TextBoxFor(x => x.Name, new { #class = "form-control" })
</div>
<div class="form-group">
#Html.Label("Father Name")
#Html.ValidationMessageFor(x => x.Fname, "", new { #class = "error" })
#Html.TextBoxFor(x => x.Fname, new { #class = "form-control" })
</div>
<div class="form-group">
#Html.Label("Email")
#Html.ValidationMessageFor(x => x.Email, "", new { #class = "error" })
#Html.TextBoxFor(x => x.Email, new { #class = "form-control" })
</div>
<div class="form-group">
#Html.Label("Mobile")
#Html.ValidationMessageFor(x => x.Mobile, "", new { #class = "error" })
#Html.TextBoxFor(x => x.Mobile, new { #class = "form-control" })
</div>
<div class="form-group">
#Html.Label("Description")
#Html.ValidationMessageFor(x => x.Description, "", new { #class = "error" })
#Html.TextBoxFor(x => x.Description, new { #class = "form-control" })
</div>
<div class="form-group">
#Html.TextBox("btn_Submit", "Submit", new { type = "Submit" })
#Html.TextBox("btn_Reset", "Reset", new { type = "Reset" })
</div>
</div>
}
DB Scripts:
CREATE TABLE [dbo].[tbl_Student]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](150) NULL,
[Fname] [varchar](150) NULL,
[Email] [varchar](150) NULL,
[Mobile] [varchar](150) NULL,
[Description] [varchar](350) NULL,
PRIMARY KEY CLUSTERED ([ID] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CRUD_logudTycoon_Revision_3.Context
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class tbl_Student
{
public int ID { get; set; }
[Required(ErrorMessage ="Name is requried")]
public string Name { get; set; }
[Required(ErrorMessage = "Father Name is requried")]
public string Fname { get; set; }
[Required(ErrorMessage = "Email is requried")]
[EmailAddress]
public string Email { get; set; }
[Required(ErrorMessage = "Mobile is requried")]
[MinLength(10,ErrorMessage ="10 Digit Mobile No. is required")]
[MaxLength(10, ErrorMessage = "10 Digit Mobile No. is required")]
public string Mobile { get; set; }
[Required(ErrorMessage = "Description is requried")]
public string Description { get; set; }
}
}

Display data in Dropdown using model with List<selectListItem>

I'm new to MVC and would like to bind data in DropDownList using Model. But I'm not sure how to get into that.
Below is my code
--Model
public string Name { get; set; }
public string Qualification { get; set; }
public string CountryID { get; set; }
public string StateID { get; set; }
public string CityID { get; set; }
public List<SelectList> CountryList { get; set; }
//public List<SelectListItem> Country { get; set; }
public List<SelectList> StateList { get; set; }
public List<SelectList> CityList { get; set; }
--View
<tr>
<td>#Html.LabelFor(s => s.Name)</td>
<td>#Html.TextBoxFor(s => s.Name, new { #class = "form-control" })</td>
</tr>
<tr>
<td>#Html.LabelFor(s => s.Qualification)</td>
<td>#Html.TextBoxFor(s => s.Qualification, new { #class = "form-control" })</td>
</tr>
<tr>
<td>#Html.LabelFor(s => s.Country)</td>
<td>#Html.DropDownList("Country", new SelectList(Model.CountryList), "Select Country", new { #Class = "form-control" })</td>
</tr>
--Controller
public ActionResult DisplayView(EmployeeDetails.Models.DisplayModel dm)
{
EmployeeDetails.Models.DisplayModel obj = new EmployeeDetails.Models.DisplayModel();
List<SelectListItem> CountryList = obj.CountryDetails(dm);
//var CountryList = obj.CountryDetails(dm);
obj.CountryList = new SelectList(CountryList, "Value", "Text");
return View();
}
In model, I have a method(CountryDetails) to return COuntrylist as List from Database.
I'm getting error in the below line to assign values to the list in model.
obj.CountryList = new SelectList(CountryList, "Value", "Text");
Please help me out to display the value correctly in Dropdown.
I have just replicated you issue and made some changes to make it run.
In Model i have made change from list<SelectList> to List<SelectListItem>
after that i have PopulateCountry dropdownlist hardcoded data in controller which you can change it by replacing it with database.
After populating dropdownlist next using jquery ajax i have populated states and city dropdownlist.
Model
public class DisplayModel
{
[Display(Name = "Choose Country")]
public string Country { get; set; }
public string Name { get; set; }
public string Qualification { get; set; }
public string CountryID { get; set; }
public string StateID { get; set; }
public string CityID { get; set; }
public List<SelectListItem> CountryList { get; set; }
public List<SelectListItem> StateList { get; set; }
public List<SelectListItem> CityList { get; set; }
}
Controller Code
public class DemoController : Controller
{
// GET: Demo
public ActionResult Index()
{
DisplayModel obj = new DisplayModel();
obj.CountryList = PopulateCountry();
return View(obj);
}
private static List<SelectListItem> PopulateCountry()
{
List<SelectListItem> li = new List<SelectListItem>();
li.Add(new SelectListItem { Text = "Select", Value = "0" });
li.Add(new SelectListItem { Text = "India", Value = "1" });
li.Add(new SelectListItem { Text = "Srilanka", Value = "2" });
return li;
}
public JsonResult GetStates(string id)
{
List<SelectListItem> states = new List<SelectListItem>();
switch (id)
{
case "1":
states.Add(new SelectListItem { Text = "Select", Value = "0" });
states.Add(new SelectListItem { Text = "ANDAMAN & NIKOBAR ISLANDS", Value = "1" });
states.Add(new SelectListItem { Text = "MAHARASHTRA", Value = "2" });
break;
}
return Json(new SelectList(states, "Value", "Text"));
}
public JsonResult GetCity(string id)
{
List<SelectListItem> City = new List<SelectListItem>();
switch (id)
{
case "2":
City.Add(new SelectListItem { Text = "Select", Value = "0" });
City.Add(new SelectListItem { Text = "MUMBAI", Value = "1" });
City.Add(new SelectListItem { Text = "PUNE", Value = "2" });
City.Add(new SelectListItem { Text = "KOLHAPUR", Value = "3" });
City.Add(new SelectListItem { Text = "RATNAGIRI", Value = "4" });
City.Add(new SelectListItem { Text = "NAGPUR", Value = "5" });
City.Add(new SelectListItem { Text = "JALGAON", Value = "6" });
break;
}
return Json(new SelectList(City, "Value", "Text"));
}
}
View
#model WebApplication1.Models.DisplayModel
#{
ViewBag.Title = "Index";
}
<table>
<tr>
<td>#Html.LabelFor(s => s.Country)</td>
<td>#Html.DropDownList("Country", Model.CountryList, "Select Country", new { #Class = "form-control" })</td>
</tr>
<tr>
<td>State</td>
<td>#Html.DropDownList("State", new SelectList(string.Empty, "Value", "Text"), "Please select a State", new { style = "width:250px", #class = "form-control" }) </td>
</tr>
<tr>
<td>City</td>
<td>#Html.DropDownList("city", new SelectList(string.Empty, "Value", "Text"), "Please select a city", new { style = "width:250px", #class = "form-control" }) </td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
//Dropdownlist Selectedchange event
$("#Country").change(function () {
$("#State").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetStates")', // we are calling json method
dataType: 'json',
data: { id: $("#Country").val() },
// here we are get value of selected country and passing same valueas inputto json method GetStates.
success: function (states) {
// states contains the JSON formatted list
// of states passed from the controller
$.each(states, function (i, state) {
$("#State").append('<option value="' + state.Value + '">' + state.Text + '</option>');
// here we are adding option for States
});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>
<script type="text/javascript">
$(document).ready(function () {
//Dropdownlist Selectedchange event
$("#State").change(function () {
$("#city").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetCity")',
dataType: 'json',
data: { id: $("#State").val() },
success: function (citys) {
// states contains the JSON formatted list
// of states passed from the controller
$.each(citys, function (i, city) {
$("#city").append('<option value="' + city.Value + '">' + city.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>

ASP.NET MVC5 - Validate against other table

Using VS2013 and building my first MVC app with EF6 (database first). I have a jobs table and a related items table (there can be millions of records per job). I need to give the user a way to export a subset of items (e.g. item 1,000 - 10,000).
So my controller contains a get method that opens a new view where they can enter the start and end values.
I want to default these to the min and max values from the items table and then I need to validate that the two numbers entered exist in the items table.
Here's my view:
#model PSAMVC.Models.Job
#{
ViewBag.Title = "ExportToLake";
}
<h2>ExportToLake</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Job</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.ID)
<div class="form-group">
#Html.LabelFor(model => model.JobNo, "JobNo", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DisplayFor(model => model.JobNo, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.VersionRef, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DisplayFor(model => model.VersionRef, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PSAJobRef, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DisplayFor(model => model.PSAJobRef, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
#Html.Label("Start Seq No", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBox("StartSeqNo")
</div>
</div>
<div class="form-group">
#Html.Label("End Seq No", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBox("EndSeqNo")
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Export" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
How/where would I enter the code to validate the two numbers against the items table?
I would think that doing in the view is the best place as the user would get immediate feedback and I can code the controller method knowing it will always be passed valid values.
I could add a view to Db that contains the job no and min and max item no, but it seems like a bit of a hack.
TIA
Mark
Update: here's my Jobs model:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace PSAMVC.Models
{
using System;
using System.Collections.Generic;
public partial class Job
{
public Job()
{
this.Items = new HashSet<Item>();
this.Reprints = new HashSet<Reprint>();
this.Scans = new HashSet<Scan>();
this.LabelTypes = new HashSet<LabelType>();
}
public int ID { get; set; }
public string JobNo { get; set; }
public string VersionRef { get; set; }
public string PSAJobRef { get; set; }
public int TotalCopies { get; set; }
public int CopiesPerBundle { get; set; }
public int CopiesPerCarton { get; set; }
public int CopiesPerMasterCarton { get; set; }
public Nullable<int> CopiesPerPallet { get; set; }
public int CardType { get; set; }
public string CardTitle { get; set; }
public string CardMMYY { get; set; }
public string StartSerialNo { get; set; }
public int StartBundleNo { get; set; }
public int StartCartonNo { get; set; }
public Nullable<int> StartMasterCartonNo { get; set; }
public Nullable<int> StartPalletNo { get; set; }
public string ProductUPC { get; set; }
public string PackagingUPC { get; set; }
public bool PreProcessed { get; set; }
public bool Completed { get; set; }
public Nullable<int> FormatFileID { get; set; }
public bool UseDummyBarcode { get; set; }
public bool Samples { get; set; }
public string PartNo { get; set; }
public string ProductEAN { get; set; }
public string PONo { get; set; }
public string ImportedFileList { get; set; }
public bool ExportedToLake { get; set; }
public Nullable<int> TotalPalletsOverride { get; set; }
public virtual CardType CardType1 { get; set; }
public virtual FormatFile FormatFile { get; set; }
public virtual ICollection<Item> Items { get; set; }
public virtual SG360JobNos SG360JobNos { get; set; }
public virtual ICollection<Reprint> Reprints { get; set; }
public virtual ICollection<Scan> Scans { get; set; }
public virtual ICollection<LabelType> LabelTypes { get; set; }
}
}
and here's my jobs controller
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using PSAMVC.Models;
using System.Data.SqlClient;
using System.Configuration;
namespace PSAMVC.Controllers
{
public class JobsController : Controller
{
private PSAMVCEntities db = new PSAMVCEntities();
// GET: Jobs
public ActionResult Index()
{
var jobs = db.Jobs.Include(j => j.CardType1).Include(j => j.FormatFile).Include(j => j.SG360JobNos);
return View(jobs.ToList());
}
// GET: Jobs/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Job job = db.Jobs.Find(id);
if (job == null)
{
return HttpNotFound();
}
return View(job);
}
// GET: Jobs/Create
public ActionResult Create()
{
ViewBag.CardType = new SelectList(db.CardTypes, "ID", "Description");
ViewBag.FormatFileID = new SelectList(db.FormatFiles, "ID", "Name");
ViewBag.JobNo = new SelectList(db.SG360JobNos, "JobNo", "JobNo");
return View();
}
// GET: CreateBundlesAndCartons
public ActionResult CreateBandC(Int32 id)
{
string ReturnMessage;
ReturnMessage = "";
using (SqlConnection connection = new SqlConnection())
{
//string connectionStringName = this.DataWorkspace.CooperData.Details.Name;
connection.ConnectionString =
ConfigurationManager.ConnectionStrings["PSAContext"].ConnectionString;
string procedure = "PSA.dbo.CreateBundlesAndCartons";
using (SqlCommand command = new SqlCommand(procedure, connection))
{
command.CommandType = CommandType.StoredProcedure;
command.CommandTimeout = 300;
command.Parameters.Add(
new SqlParameter("#JobID", id));
SqlParameter ErrorString = new SqlParameter("#ErrorString", ReturnMessage);
ErrorString.Direction = ParameterDirection.Output;
ErrorString.Size = 4000;
command.Parameters.Add(ErrorString);
connection.Open();
command.ExecuteNonQuery();
// Save Outout Param
ReturnMessage = ErrorString.Value.ToString();
#ViewBag.Results = ReturnMessage;
}
}
//return Content("You requested the to create bundles and cartons for job ID " + id.ToString() + "<br />Result: " + ReturnMessage + "<br /> Return to Jobs");
return PartialView("_SPResults");
}
// GET: Jobs/ExportToLake/5
public ActionResult ExportToLake(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Job job = db.Jobs.Find(id);
if (job == null)
{
return HttpNotFound();
}
ViewBag.JobNo = new SelectList(db.SG360JobNos, "JobNo", "JobNo", job.JobNo);
return View(job);
}
// GET: ExportToLake1
public ActionResult ExportToLake1(Int32 id, Int64 StartSeqNo, Int64 EndSeqNo, Boolean ReverseOrder, String FileNameSuffix)
{
string ReturnMessage;
ReturnMessage = "";
using (SqlConnection connection = new SqlConnection())
{
//string connectionStringName = this.DataWorkspace.CooperData.Details.Name;
connection.ConnectionString =
ConfigurationManager.ConnectionStrings["PSAContext"].ConnectionString;
string procedure = "PSA.dbo.ExportToLakeBulk";
using (SqlCommand command = new SqlCommand(procedure, connection))
{
command.CommandType = CommandType.StoredProcedure;
command.CommandTimeout = 1200;
command.Parameters.Add(
new SqlParameter("#JobID", id));
command.Parameters.Add(
new SqlParameter("#ReverseOrder", ReverseOrder));
command.Parameters.Add(
new SqlParameter("#StartSeqNo", StartSeqNo));
command.Parameters.Add(
new SqlParameter("#EndSeqNo", EndSeqNo));
command.Parameters.Add(
new SqlParameter("#Suffix", FileNameSuffix));
SqlParameter ErrorString = new SqlParameter("#ErrorString", ReturnMessage);
ErrorString.Direction = ParameterDirection.Output;
ErrorString.Size = 4000;
command.Parameters.Add(ErrorString);
connection.Open();
command.ExecuteNonQuery();
// Save Outout Param
ReturnMessage = ErrorString.Value.ToString();
#ViewBag.Results = ReturnMessage;
}
}
//return Content("You requested the to create bundles and cartons for job ID " + id.ToString() + "<br />Result: " + ReturnMessage + "<br /> Return to Jobs");
return PartialView("_SPResults");
}
// POST: Jobs/ExportToLake
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ExportToLake2([Bind(Include = "ID,StartSeqNo,EndSeqNo,ReverseOrder")] Job job)
{
if (ModelState.IsValid)
{
//db.Jobs.Add(job);
//db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CardType = new SelectList(db.CardTypes, "ID", "Description", job.CardType);
ViewBag.FormatFileID = new SelectList(db.FormatFiles, "ID", "Name", job.FormatFileID);
ViewBag.JobNo = new SelectList(db.SG360JobNos, "JobNo", "JobNo", job.JobNo);
return View(job);
}
// POST: Jobs/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,JobNo,VersionRef,PSAJobRef,TotalCopies,CopiesPerBundle,CopiesPerCarton,CopiesPerMasterCarton,CopiesPerPallet,CardType,CardTitle,CardMMYY,StartSerialNo,StartBundleNo,StartCartonNo,StartMasterCartonNo,StartPalletNo,ProductUPC,PackagingUPC,PreProcessed,Completed,FormatFileID,UseDummyBarcode,Samples,PartNo,ProductEAN,PONo,ImportedFileList,ExportedToLake,TotalPalletsOverride")] Job job)
{
if (ModelState.IsValid)
{
db.Jobs.Add(job);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CardType = new SelectList(db.CardTypes, "ID", "Description", job.CardType);
ViewBag.FormatFileID = new SelectList(db.FormatFiles, "ID", "Name", job.FormatFileID);
ViewBag.JobNo = new SelectList(db.SG360JobNos, "JobNo", "JobNo", job.JobNo);
return View(job);
}
// GET: Jobs/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Job job = db.Jobs.Find(id);
if (job == null)
{
return HttpNotFound();
}
ViewBag.CardType = new SelectList(db.CardTypes, "ID", "Description", job.CardType);
ViewBag.FormatFileID = new SelectList(db.FormatFiles, "ID", "Name", job.FormatFileID);
ViewBag.JobNo = new SelectList(db.SG360JobNos, "JobNo", "JobNo", job.JobNo);
return View(job);
}
// POST: Jobs/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ID,JobNo,VersionRef,PSAJobRef,TotalCopies,CopiesPerBundle,CopiesPerCarton,CopiesPerMasterCarton,CopiesPerPallet,CardType,CardTitle,CardMMYY,StartSerialNo,StartBundleNo,StartCartonNo,StartMasterCartonNo,StartPalletNo,ProductUPC,PackagingUPC,PreProcessed,Completed,FormatFileID,UseDummyBarcode,Samples,PartNo,ProductEAN,PONo,ImportedFileList,ExportedToLake,TotalPalletsOverride")] Job job)
{
if (ModelState.IsValid)
{
db.Entry(job).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CardType = new SelectList(db.CardTypes, "ID", "Description", job.CardType);
ViewBag.FormatFileID = new SelectList(db.FormatFiles, "ID", "Name", job.FormatFileID);
ViewBag.JobNo = new SelectList(db.SG360JobNos, "JobNo", "JobNo", job.JobNo);
return View(job);
}
// GET: Jobs/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Job job = db.Jobs.Find(id);
if (job == null)
{
return HttpNotFound();
}
return View(job);
}
// POST: Jobs/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Job job = db.Jobs.Find(id);
db.Jobs.Remove(job);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
Firstly the server side code should not assume that the values being passed are valid. Always validate the values and handle errors correctly. Client side validation can be bypassed.
In terms of providing instant feedback, one approach is to have an action on a controller that accepts the value to validate as a parameter and returns json containing whether the value was valid and if not the error.
This action can then be called on the input fields blur event or change even providing close to real time feedback on whether the values are valid.
Another approach is to have the valid values determined during the page rendering process and embedded into the client side validation framework if you have one (or use custom JS).
Client Code
function performValidate(data, url) {
var result = $.ajax({
type: "POST",
url: url,
data: data,
success: function (data) {
if (!data.success) {
//HandleIncorrectValue
}
//HandleCorrectValue
},
error: function (data) {
//HandleError
}
});
Controller Code
[HttpPost]
public ActionResult Validate(int value)
{
var response = ValidateValue(value);
return Json(new { success = response.Success, message = response.Message });
}

I want to fill city dropdown automatically from database according to state dropdown in ASP.NET MVC and Ajax

I want to get city list from database and store selected city's id into database. I have used Ajax to call function of member class. But it is not working, please help me to sort this out.
Here is my Model:
[Required]
[Display(Name = "State")]
public int stateid { get; set; }
public string stateName { get; set; }
public List<SelectListItem> stateList = new List<SelectListItem>();
[Required]
[Display(Name = "City")]
public int Cityid { get; set; }
public string CityName { get; set; }
public List<SelectListItem> CityList = new List<SelectListItem>();
clubDataContext cd = new clubDataContext();
public void insertmember(M_Reg m)
{
M_Registarion m1 = new M_Registarion();
m1.M_StatteId = m.stateid;
m1.M_CityId = 1; //temporary storing 1
cd.M_Registarions.InsertOnSubmit(m1);
cd.SubmitChanges();
}
Here is my controller:
[HttpGet]
public ActionResult Registration()
{
var model = new M_Reg();
using (var db = new clubDataContext())
{
model.stateList = content2.Select(c2 => new SelectListItem
{
Text = c2.S_Name,
Value = c2.S_ID.ToString()
}).ToList();
}
return View(model);
}
[HttpGet]
public SelectList getCity(int stateId, int selectCityId)
{
var db = new clubDataContext();
var model = new M_Reg();
var content = from p in db.CityInfos where p.S_ID == stateId
select new { p.C_ID, p.C_Name };
model.CityList = content.Select(c => new SelectListItem
{
Text = c.C_Name,
Value = c.C_ID.ToString()
}).ToList();
return new SelectList(model.CityList, "Value", "Text", selectCityId);
}
View:
Razor code:
<div class="editor-label">
#Html.LabelFor(m=> m.stateid)
</div>
<div class="editor-field">
#Html.DropDownListFor(m => m.stateid,Model.stateList)
#Html.ValidationMessageFor(m => m.stateid)
</div>
<div class="editor-label">
#Html.LabelFor(m=> m.Cityid)
</div>
<div class="editor-field">
#Html.DropDownListFor(m => m.Cityid, Model.CityList)
#Html.ValidationMessageFor(m => m.Cityid, Model.c)
</div>
Ajax code:
$("#stateid").change(function () {
$.ajax({
type: "POST",
url: '#Url.Action("Member", "getCity")',
data: { stateId: $("#stateid > option:selected").attr("value") },
success: function (data) {
var items = [];
items.push("<option>--Choose Your City--</option>");
$.each(data, function () {
items.push("<option value=" + this.Value + ">" + this.Text + "</option>");
});
$("#Cityid").html(items.join(' '));
}
})
});
Try Like This
Here Controller :
public JsonResult functionname(){
List<string> City = new List<string>();
var DBcity = yourDBentity.TableName.Where(x=>x.columnname==condition).select(x=>x.city);
foreach(var i in DBcity){
City.Add(i);
}
return Json(City, JsonRequestBehavior.AllowGet);
}
Jquery:
$(document).ready(function (result) {
$.post('/yourcontorller/functionname', {parameter : parameter }, function (result) {
$.each(result, function (key, value) {
$('#yourDropdownId').append($("<option></option>").html(value).val(value));
});
},"json");
});
Finally, this code works...
Model Class:
clubDataContext _db = new clubDataContext();
[Required]
[Display(Name="City")]
public virtual string icityid { get; set; }
public List<SelectListItem> cityList = new List<SelectListItem>();
[Required]
[Display(Name = "State")]
public virtual string istateid { get; set; }
public SelectList getState()
{
IEnumerable<SelectListItem> stateList = (from m in _db.StateInfos select m).AsEnumerable().Select(m => new SelectListItem() { Text = m.S_Name, Value = m.S_ID.ToString() });
return new SelectList(stateList, "Value", "Text", istateid);
}
View :
<div class="editor-label">
#Html.LabelFor(m=> m.istateid)
</div>
<div class="editor-field">
#Html.DropDownListFor(m => m.istateid,Model.getState(),"--Choose your State--")
#Html.ValidationMessageFor(m => m.istateid)
</div>
<div class="editor-label">
#Html.LabelFor(m=> m.icityid)
</div>
<div class="editor-field">
#Html.DropDownListFor(m => m.icityid,Model.cityList,"--Choose your City--")
#Html.ValidationMessageFor(m => m.icityid)
</div>
Ajax:
$('#istateid').change(function(){
$.ajax({
type:"POST",
url:'#Url.Action("getCityJson","Member")',
data: { stateId : $("#istateid > option:selected").attr("value")},
success: function (data){
var items= [];
$.each(data,function(){
items.push("<option value=" + this.Value + ">" + this.Text + "</option>");
});
$("#icityid").html(items.join(' '));
}
})
});
And Controller:
[HttpPost]
public JsonResult getCityJson(string stateId, string selectCityId=null)
{
return Json(getCity(stateId, selectCityId));
}
public SelectList getCity(string stateId, string selectCityId = null)
{
var db = new clubDataContext();
IEnumerable<SelectListItem> cityList = new List<SelectListItem>();
if (!string.IsNullOrEmpty(stateId))
{
int _stateId = Convert.ToInt32(stateId);
cityList = (from m in db.CityInfos where m.S_ID == _stateId select m).AsEnumerable().Select(m => new SelectListItem() { Text = m.C_Name, Value = m.C_ID.ToString() });
}
return new SelectList(cityList, "Value", "Text", selectCityId);
}

asp.net mvc Send form from site to email

I have feedback form on my mvc site, it looks like
I created model for my form
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ComponentTrading.Web.Models
{
public class FeedbackForm
{
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Message { get; set; }
}
}
I created view for my form
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "contact-form" }))
{
<fieldset>
#Html.TextBoxFor(model => model.Name, new { #Value = "Name" })
#Html.TextBoxFor(model => model.Email, new { #Value = "E-mail" })
#Html.TextBoxFor(model => model.Phone, new { #Value = "Phone" })
#Html.TextAreaFor(model => model.Message, new { #class = "img-shadow"})
<input class="form-button" data-type="reset" value="Clear" />
<input class="form-button" data-type="submit" type="submit" value="Send" />
}
and now i try to do a sending a letter to email, but it doesn work, when I push "send-button" it happens nothing and I dont get email
my controller
[HttpGet]
public ActionResult Contacts()
{
FeedbackForm temp = new FeedbackForm();
temp.Message = "Message";
return View(temp);
}
[HttpPost]
public ActionResult Contacts(FeedbackForm Model)
{
string Text = "<html> <head> </head>" +
" <body style= \" font-size:12px; font-family: Arial\">"+
Model.Message+
"</body></html>";
SendEmail("mironny#inbox.ru", Text);
FeedbackForm temp = new FeedbackForm();
return View(temp);
}
public static bool SendEmail(string SentTo, string Text)
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress("Test#mail.ru");
msg.To.Add(SentTo);
msg.Subject = "Password";
msg.Body = Text;
msg.Priority = MailPriority.High;
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.mail.ru", 25);
client.UseDefaultCredentials = false;
client.EnableSsl = false;
client.Credentials = new NetworkCredential("TestLogin", "TestPassword");
client.DeliveryMethod = SmtpDeliveryMethod.Network;
//client.EnableSsl = true;
try
{
client.Send(msg);
}
catch (Exception)
{
return false;
}
return true;
}
what's wrong?
Use
// if you dont pass any parameter
// BeginForm posted to the action that
// has name as view name.
// so no need to write any parameters
#using (Html.BeginForm())
{
...
<input type="submit" value="Send">
}
OR
#using (Html.BeginForm("Contacts", "SomeController", FormMethod.Post, new { id = "contact-form" }))
{
...
<input type="submit" value="Send">
}
You have a few question about mvc and there is more important thing of them is incorrect overload methods. My suggestion, first, you should learn html-helpers overload methods. And MVC model binding strategies...

Resources