I want to send an email with a file attachment. when I client send and use the break to check what is the data I am receiving then image file show null in the controller. anyone tells me where is my mistake and what is the problem in my code.so i am sharing controller code ,model and HTML kindly review my code and tell me what is the problem in my code.
Controller
[HttpPost]
public ActionResult Index(EmployeeModel obj)
{
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("abc#hotmail.com", "******");
MailMessage msgobj = new MailMessage();
msgobj.To.Add(obj.ToEmail);
msgobj.From = new MailAddress("abc#hotmail.com");
msgobj.Body = obj.EMailBody;
msgobj.Subject = obj.EmailSubject;
msgobj.CC.Add(obj.EmailCC);
msgobj.Bcc.Add(obj.EmailBCC);
if(obj.imageFile !=null)
{
msgobj.Attachments.Add(new Attachment(obj.imageFile.InputStream.ToString(), obj.imageFile.FileName));
}
client.Send(msgobj);
ViewBag.Success = "Email Send Successfully";
return View();
}
Model:
[DataType(DataType.EmailAddress),Display(Name = "TO")]
[Required]
[Key]
public string ToEmail { get; set; }
[DataType(DataType.MultilineText)]
[Display(Name ="Body")]
[Required]
public string EMailBody { get; set; }
[Display(Name ="Subject")]
[Required]
public string EmailSubject { get; set; }
[Display(Name ="CC")]
[DataType(DataType.EmailAddress)]
public string EmailCC { get; set; }
[Display(Name ="BCC")]
[DataType(DataType.EmailAddress)]
public string EmailBCC { get; set; }
public HttpPostedFileWrapper imageFile { get; set; }
public string imageUrl { get; set; }
HTML
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Employee Model</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ToEmail, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ToEmail, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ToEmail, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EMailBody, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EMailBody, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EMailBody, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EmailSubject, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EmailSubject, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EmailSubject, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EmailCC, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EmailCC, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EmailCC, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EmailBCC, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EmailBCC, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EmailBCC, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.imageFile, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" id="imageFile" name="imageFile" accept="image/jpeg, image/png" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Send" class="btn btn-default" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10 text-success">
#ViewBag.Status
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
First, you should modify this property:
public HttpPostedFileWrapper imageFile { get; set; }
to this one:
public HttpPostedFileBase imageFile { get; set; }
Second, add enctype="multipart/form-data to the BeginForm helper:
#using (Html.BeginForm("Index", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
// form contents
}
Also you're using Gmail SMTP engine but your network credential setting seem to use Hotmail, both of them have different settings. Here are examples of correct settings:
Gmail SMTP
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("xxxxx#gmail.com", "******");
MailMessage msgobj = new MailMessage();
msgobj.To.Add(obj.ToEmail);
msgobj.From = new MailAddress("xxxxx#gmail.com");
msgobj.Body = obj.EMailBody;
msgobj.Subject = obj.EmailSubject;
msgobj.CC.Add(obj.EmailCC);
msgobj.Bcc.Add(obj.EmailBCC);
if (obj.imageFile != null && obj.imageFile.ContentLength > 0)
{
msgobj.Attachments.Add(new Attachment(obj.imageFile.InputStream, obj.imageFile.FileName));
}
client.Send(msgobj);
Hotmail SMTP
SmtpClient client = new SmtpClient("smtp.live.com", 587);
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("xxxxx#hotmail.com", "******");
MailMessage msgobj = new MailMessage();
msgobj.To.Add(obj.ToEmail);
msgobj.From = new MailAddress("xxxxx#hotmail.com");
msgobj.Body = obj.EMailBody;
msgobj.Subject = obj.EmailSubject;
msgobj.CC.Add(obj.EmailCC);
msgobj.Bcc.Add(obj.EmailBCC);
if (obj.imageFile != null && obj.imageFile.ContentLength > 0)
{
msgobj.Attachments.Add(new Attachment(obj.imageFile.InputStream, obj.imageFile.FileName));
}
client.Send(msgobj);
you should change
#using (Html.BeginForm())
with
#using (Html.BeginForm("Index", "YourControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
What does enctype='multipart/form-data' mean?
Related
I have to upload simple data to my server but in create page after I enter data and submit it, it doesn't no upload the data to database but it works fine as it returns to index menu and shows all other entries in database just it won't upload any new data
Create page
No Changes occur to database but data s fetched properly
following are the codes
Html for 'create page'
#model SnackoEntities.DealMasterInfo
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>DealMasterInfo</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.DealAutoID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DealAutoID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DealAutoID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FK_RestoID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FK_RestoID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FK_RestoID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FK_SnFoodID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FK_SnFoodID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FK_SnFoodID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FK_RoFoodID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FK_RoFoodID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FK_RoFoodID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DealDisPerc, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DealDisPerc, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DealDisPerc, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FK_RewaID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FK_RewaID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FK_RewaID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.startDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.startDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.startDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.endDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.endDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.endDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ValidOn, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ValidOn, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ValidOn, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserTypes, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserTypes, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UserTypes, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DealCode, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DealCode, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DealCode, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DealPic, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DealPic, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DealPic, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DealStatus, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DealStatus, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DealStatus, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CreatedOn, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CreatedOn, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CreatedOn, "", new { #class = "text-danger" })
</div>
</div>q
<div class="form-group">
#Html.LabelFor(model => model.ModifiedOn, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ModifiedOn, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ModifiedOn, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CreatedBy, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CreatedBy, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CreatedBy, "", new { #class = "text-danger" })
</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>
#Html.ActionLink("Back to List", "Index")
</div>
My controller
[HttpGet]
[ActionName("Create")]
public ActionResult Create_get()
{
return View();
}
[HttpPost]
[ActionName("Create")]
public ActionResult Create_post(DealMasterInfo dealMasterInfo)
{
if (ModelState.IsValid)
{
//DealMasterInfo dealMasterInfo = new DealMasterInfo();
UpdateModel(dealMasterInfo);
DealMasterBLL dealMasterBLL = new DealMasterBLL();
dealMasterBLL.AddDealMaster(dealMasterInfo);
if (dealMasterInfo != null)
{
return RedirectToAction("Index");
}
}
return View();
}
Bll code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using SnackoEntities;
namespace BusinesssLayer
{
public class DealMasterBLL
{
public IEnumerable<DealMasterInfo> DealMasterInfo
{
get
{
string connectionString = ConfigurationManager.ConnectionStrings["DealMaster"].ConnectionString;
List<DealMasterInfo> dealMasterInfos = new List<DealMasterInfo>();
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("spGetDealMasterInfo", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
DealMasterInfo dealMasterInfo = new DealMasterInfo();
dealMasterInfo.DealAutoID = rdr["DealAutoID"].ToString();
dealMasterInfo.FK_RestoID = rdr["FK_RestoID"].ToString();
dealMasterInfo.FK_SnFoodID = rdr["FK_SnFoodID"].ToString();
dealMasterInfo.DealDisPerc = rdr["DealDisPerc"].ToString();
dealMasterInfo.FK_RewaID = rdr["FK_RewaID"].ToString();
dealMasterInfo.startDate = Convert.ToDateTime(rdr["startDate"]);
dealMasterInfo.endDate = Convert.ToDateTime(rdr["endDate"]);
dealMasterInfo.ValidOn = rdr["ValidOn"].ToString();
dealMasterInfo.UserTypes = rdr["UserTypes"].ToString();
dealMasterInfo.DealCode = rdr["DealCode"].ToString();
dealMasterInfo.DealPic = rdr["DealPic"].ToString();
dealMasterInfo.DealStatus = rdr["DealStatus"].ToString();
dealMasterInfo.CreatedOn = Convert.ToDateTime(rdr["CreatedOn"]);
dealMasterInfo.ModifiedOn = Convert.ToDateTime(rdr["ModifiedOn"]);
dealMasterInfo.CreatedBy = rdr["CreatedBy"].ToString();
dealMasterInfos.Add(dealMasterInfo);
}
}
return dealMasterInfos;
}
}
public void AddDealMaster(DealMasterInfo dealMasterInfo)
{
string connectionString = ConfigurationManager.ConnectionStrings["DealMaster"].ConnectionString;
try
{
using(SqlConnection con=new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("spAddDealMaster", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramDealAutoID = new SqlParameter();
paramDealAutoID.ParameterName = "#DealAuto";
paramDealAutoID.Value = dealMasterInfo.DealAutoID;
cmd.Parameters.Add(paramDealAutoID);
SqlParameter paramFK_RestoID = new SqlParameter();
paramFK_RestoID.ParameterName = "#FK_RestoID";
paramFK_RestoID.Value = dealMasterInfo.FK_RestoID;
cmd.Parameters.Add(paramFK_RestoID);
SqlParameter paramFK_SnFoodID = new SqlParameter();
paramFK_SnFoodID.ParameterName = "#FK_SnFoodID";
paramFK_SnFoodID.Value = dealMasterInfo.FK_SnFoodID;
cmd.Parameters.Add(paramFK_SnFoodID);
SqlParameter paramFK_RoFoodID = new SqlParameter();
paramFK_RoFoodID.ParameterName = "#FK_RoFoodID";
paramFK_RoFoodID.Value = dealMasterInfo.FK_RoFoodID;
cmd.Parameters.Add(paramFK_RoFoodID);
SqlParameter paramDealDisPerc = new SqlParameter();
paramDealDisPerc.ParameterName = "#DealDisPerc";
paramDealDisPerc.Value = dealMasterInfo.DealDisPerc;
cmd.Parameters.Add(paramDealDisPerc);
SqlParameter paramFK_RewaID = new SqlParameter();
paramFK_RewaID.ParameterName = "#FK_RewaID";
paramFK_RewaID.Value = dealMasterInfo.FK_RewaID;
cmd.Parameters.Add(paramFK_RewaID);
SqlParameter paramstartDate = new SqlParameter();
paramstartDate.ParameterName = "#startDate";
paramstartDate.Value = dealMasterInfo.startDate;
cmd.Parameters.Add(paramstartDate);
SqlParameter paramendDate = new SqlParameter();
paramendDate.ParameterName = "#endDate";
paramendDate.Value = dealMasterInfo.endDate;
cmd.Parameters.Add(paramendDate);
SqlParameter paramValidOn = new SqlParameter();
paramValidOn.ParameterName = "#ValidOn";
paramValidOn.Value = dealMasterInfo.ValidOn;
cmd.Parameters.Add(paramValidOn);
SqlParameter paramUserTypes = new SqlParameter();
paramUserTypes.ParameterName = "#UserTypes";
paramUserTypes.Value = dealMasterInfo.UserTypes;
cmd.Parameters.Add(paramUserTypes);
SqlParameter paramDealCode = new SqlParameter();
paramDealCode.ParameterName = "#DealCode";
paramDealCode.Value = dealMasterInfo.DealCode;
cmd.Parameters.Add(paramDealCode);
SqlParameter paramDealPic = new SqlParameter();
paramDealPic.ParameterName = "#DealPic";
paramDealPic.Value = dealMasterInfo.DealPic;
cmd.Parameters.Add(paramDealPic);
SqlParameter paramDealStatus = new SqlParameter();
paramDealStatus.ParameterName = "#DealStatus";
paramDealStatus.Value = dealMasterInfo.DealStatus;
cmd.Parameters.Add(paramDealStatus);
SqlParameter paramCreatedOn = new SqlParameter();
paramCreatedOn.ParameterName = "#CreatedOn";
paramCreatedOn.Value = dealMasterInfo.CreatedOn;
cmd.Parameters.Add(paramCreatedOn);
SqlParameter paramModifiedOn = new SqlParameter();
paramModifiedOn.ParameterName = "#ModifiedOn";
paramModifiedOn.Value = dealMasterInfo.ModifiedOn;
cmd.Parameters.Add(paramModifiedOn);
SqlParameter paramCreatedBy = new SqlParameter();
paramCreatedBy.ParameterName = "#CreatedBy";
paramCreatedBy.Value = dealMasterInfo.CreatedBy;
cmd.Parameters.Add(paramCreatedBy);
con.Open();
cmd.ExecuteNonQuery();
}
}
catch(Exception ex){
Console.WriteLine("SQL Error" + ex.Message.ToString());
}
}
}
}
entity class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SnackoEntities
{
public class DealMasterInfo
{
public string DealAutoID { get; set; }
public string FK_RestoID { get; set; }
public string FK_SnFoodID { get; set; }
public string FK_RoFoodID { get; set; }
public string DealDisPerc { get; set; }
public string FK_RewaID { get; set; }
public DateTime startDate { get; set; }
public DateTime endDate { get; set; }
public string ValidOn { get; set; }
public string UserTypes { get; set; }
public string DealCode { get; set; }
public string DealPic { get; set; }
public string DealStatus { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime ModifiedOn { get; set; }
public string CreatedBy { get; set; }
}
}
I am learning MVC and this is my first project, so please with the solution give an explanation in easy language so that I can understand the problem in future
There was a spelling mistake in the code due to which it wasn't working
the
SqlParameter paramDealDisPerc = new SqlParameter();
paramDealDisPerc.ParameterName = "#DealDisPerc";
paramDealDisPerc.Value = dealMasterInfo.DealDisPerc;
cmd.Parameters.Add(paramDealDisPerc);
here the DealDiscPerc Should have been DealDiscPerc
SqlParameter paramDealDisPerc = new SqlParameter();
paramDealDisPerc.ParameterName = "#DealDiscPerc";
paramDealDisPerc.Value = dealMasterInfo.DealDisPerc;
cmd.Parameters.Add(paramDealDisPerc);
did this mistake because my table had same variable without "C" whereas while writing SP i added a "C" and this caused the confusion
this solved the issue
I know that the question was asked and answered many times, but unfortunately no one of the answers helped me.
I have tree POCO models, which are Pharmacy, Address and Company gathered together into a ViewModel PharmacyVM:
public class PharmacyVM
{
public Pharmacy pharmacyProp { get; set; }
public Address addressProp { get; set; }
public Company companyProp { get; set; }
public int CityId { get; set; }
public PharmacyVM()
{
pharmacyProp = new Pharmacy();
addressProp = new Address();
companyProp = new Company();
}
}
Don't laugh at the properties names; at the start, they had been normal (Address, Company and Pharmacy) I changed them according to one of the lots of answers in here, but... it didn't help :(
In the Get action of the Create method I'm trying to manually create the PharmacyVM object and pass it to the view:
public ActionResult Create()
{
ViewBag.CityId = new SelectList(db.Cities, "Id", "Name");
ViewBag.CompanyId = new SelectList(db.Companies, "Id", "Name");
ViewBag.AddressId = new SelectList(db.Addresses, "Id", "Name");
ViewBag.CityId = new SelectList(db.Cities, "Id", "Name");
ViewBag.RegionId = new SelectList(db.Regions, "Id", "Name");
ViewBag.DistrictId = new SelectList(db.Districts, "Id", "Name");
ViewBag.MicrodistrictId = new SelectList(db.Microdistricts, "Id", "Name");
ViewBag.StreetId = new SelectList(db.Streets, "Id", "Name");
ViewBag.VillageId = new SelectList(db.Villages, "Id", "Name");
var pharmacyVM = new PharmacyVM();
return View(pharmacyVM);
}
There is a standard Razor code in the view:
#model MEDONET.Models.PharmacyVM
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm("Create", "Pharmacies", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>pharmacyProp</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.companyProp, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("CompanyId", null, "", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.companyProp.Id, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.pharmacyProp.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.pharmacyProp.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.pharmacyProp.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.addressProp.City, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("CityId", null, "", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CityId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CityId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("CityId", null, "", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CityId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.addressProp.Village, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("VillageId", null, "", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.addressProp.VillageId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.addressProp.District, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("DistrictId", null, "", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.addressProp.DistrictId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.HiddenFor(model => model.addressProp.RegionId)
#Html.LabelFor(model => model.addressProp.Region, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("RegionId", null, "", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.addressProp.RegionId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.addressProp.Microdistrict, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("MicrodistrictId", null, "", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.addressProp.MicrodistrictId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.addressProp.Building, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.addressProp.Building, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.addressProp.Building, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.addressProp.Street, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("MicrodistrictId", null, "", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.addressProp.MicrodistrictId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.pharmacyProp.IsGov, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.pharmacyProp.IsGov)
#Html.ValidationMessageFor(model => model.pharmacyProp.IsGov, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.companyProp, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("companyId", null, "", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.pharmacyProp.CompanyId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.pharmacyProp.LargeImage, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="LargeImageFile" required />
</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> #Html.ActionLink("Back to List", "Index")</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
And then in the Post action of the Create method, I'm trying to create b and c variables:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(PharmacyVM model, HttpPostedFileBase LargeImageFile)
{
if (ModelState.IsValid)
{
string LargeImageFileName = Path.GetFileNameWithoutExtension(LargeImageFile.FileName);
string LargeImageExtansion = Path.GetExtension(LargeImageFile.FileName);
LargeImageFileName = LargeImageFileName + DateTime.Now.ToString("yymmssfff") + LargeImageExtansion;
LargeImageFileName = Path.Combine(Server.MapPath("~/Images/Pharmacy/Banners/"), LargeImageFileName);
int b = model.CityId;
int c = model.addressProp.RegionId.Value;
//Address address = new Address()
//{
// Id = 12,//db.Addresses.AsEnumerable().Last().Id + 1,
// RegionId = PharmacyVM.Address.RegionId,
// DistrictId = PharmacyVM.Address.DistrictId,
// CityId = PharmacyVM.Address.CityId,
// MicrodistrictId = PharmacyVM.Address.MicrodistrictId,
// StreetId = PharmacyVM.Address.StreetId,
// VillageId = PharmacyVM.Address.VillageId,
// Building = PharmacyVM.Address.Building,
// Cab = PharmacyVM.Address.Cab
//};
//Address address = new Address
//{
// Id = 12,//db.Addresses.AsEnumerable().Last().Id + 1,
// RegionId = 1,
// DistrictId = 1,
// CityId = 1,
// MicrodistrictId = 1,
// StreetId = 1,
// VillageId = 1,
// Building = "1",
// Cab = "1"
//};
//db.Addresses.Add(address);
db.SaveChanges();
var pharmacy = new Pharmacy
{
Name = model.pharmacyProp.Name,
//AddressId = address.Id,
IsGov = model.pharmacyProp.IsGov,
CompanyId = model.pharmacyProp.CompanyId,
LargeImage = "~/Images/Pharmacy/Banners/" + LargeImageFileName
};
LargeImageFile.SaveAs(LargeImageFileName);
db.Pharmacies.Add(pharmacy);
db.SaveChanges();
ModelState.Clear();
return RedirectToAction("Index");
}
}
Unlike first variable b, the second one c is gonna be null because the addressProp property is null.
So why is it so strange? How can I use ViewModel without duplicating original model's fields?
why are you use
int b= model.addressProp.RegionId.Value
instead of
int b=model.addressProp.RegionId
Even for your good cording the best and good way is remove all View bag and
Add all View bag properties to PharmacyVM Class
Dont use two properties for view binding
Example
public class PharmacyVM
{
public Pharmacy pharmacyProp { get; set; }
public Address addressProp { get; set; }
public Company companyProp { get; set; }
public int CityId { get; set; }
public SelectList CityIdList { get; set; }
public PharmacyVM()
{
pharmacyProp = new Pharmacy();
addressProp = new Address();
companyProp = new Company();
CityIdList =new SelectList(db.Cities, "Id", "Name");
}
}
public ActionResult Create()
{
var pharmacyVM = new PharmacyVM();
return View(pharmacyVM);
}
#model PharmacyVM
#using (Html.BeginForm())
{
#Html.HiddenFor(m => m.CityId )
<div class="editor-label">
#Html.LabelFor(m => m.Name)
</div>
<div class="editor-field">
#Html.EditorFor(m => m.Name)
#Html.ValidationMessageFor(m => m.Name)
</div>
<button type="submit">Create</button>
}
[HttpPost]
public ActionResult Create(PharmacyVM model)
{
int c = model.addressProp
return View(viewModel);
}
More Information
I am trying to populate a dropdownlist and then post it to db but for some reason it is giving error, please advice.
Controller
public class StudentController : BaseController
{
private List<SelectListItem> _gendersList;
[HttpGet]
public ActionResult Create()
{
var model = new CreateStudent();
_gendersList = new List<SelectListItem>()
{
new SelectListItem { Text = Constants.Gender.Boy, Value = Constants.Gender.Boy},
new SelectListItem { Text = Constants.Gender.Girl, Value = Constants.Gender.Girl},
};
model.Genders = _gendersList;
return View(model);
}
[HttpPost]
public ActionResult Create(CreateStudent student)
{
var result = true;
_gendersList = new List<SelectListItem>()
{
new SelectListItem { Text = Constants.Gender.Boy, Value = Constants.Gender.Boy},
new SelectListItem { Text = Constants.Gender.Girl, Value = Constants.Gender.Girl},
};
if (ModelState.IsValid)
{
result = _student.Insert(mappedStudent);
if (result)
{
return RedirectToAction("Index");
}
else
{
TempData["Message"] = "Failed to create new student";
return View();
}
}
return View("Create");
}
}
View
#model CreateStudent
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="~/Scripts/jquery-3.1.1.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<h2>Create</h2>
#{
if (TempData["Message"] != null)
{
<h3>
#TempData["Message"].ToString()
</h3>
}
}
#{
}
#using (Html.BeginForm("Create","Student",FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Student</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.MiddleName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(model => model.MiddleName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MiddleName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Gender, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.DropDownListFor(o=>o.Gender,Model.StudentGender, "", new { #class = "form-control" })*#
#Html.DropDownListFor(o=>o.Gender,(List<SelectListItem>)Model.Genders,"1", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Gender, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.IdNo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.IdNo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.IdNo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SchoolIdNo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SchoolIdNo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SchoolIdNo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ServiceType, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ServiceType, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ServiceType, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Comments, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Comments, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Comments, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.IsEnabled, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.IsEnabled)
#Html.ValidationMessageFor(model => model.IsEnabled, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FirstNameAr, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FirstNameAr, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstNameAr, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.MiddleNameAr, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MiddleNameAr, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MiddleNameAr, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastNameAr, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LastNameAr, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastNameAr, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Your view is strongly typed to a CreateStudent class and the view code is using Model.Genders collection property when you use the DropDownListFor helper method. But in your http post action, you are calling the return View() method without passing a valid CreateStudent object and in another case without populating the Genders property. So when razor executes the view code, the model value is null ( because you did not pass anything to the view)
You need to set the Genders property again before returning the posted view model back to the view.
[HttpPost]
public ActionResult Create(CreateStudent student)
{
var genderList = new List<SelectListItem>()
{
new SelectListItem { Text = Constants.Gender.Boy, Value = Constants.Gender.Boy},
new SelectListItem { Text = Constants.Gender.Girl, Value = Constants.Gender.Girl},
};
if (ModelState.IsValid)
{
var result = _student.Insert(mappedStudent);
if (result)
{
return RedirectToAction("Index");
}
else
{
student.Genders = genderList;
TempData["Message"] = "Failed to create new student";
return View(student); // Passing the object here to view
}
}
//Model validation fails. Return the same view
student.Genders = genderList;
return View(student);
}
}
Also there no need for an extra casting. Model.Genders is of type List<SelectListItem>
#Html.DropDownListFor(o=>o.Gender,Model.Genders, new { #class = "form-control" })
I would want to insert multiple entries in my table called 'sibling' using it's Create Method (which I generated automatically using Scaffolding methods). I already made the form dynamic in adding the fields. However, when I click on the Submit button it only gets the first entry.
I sort of have an idea by implementing 'foreach' in the said method but I can't seem to find an answer that is spot on. Especially for my case I just want to modify the Create Method for 'sibling' which was generated automatically (if there is such a way without having to create a new method - but if not I am fine with a different approach as well).
This is my SiblingController:
public ActionResult Create(int id)
{
var sib = new sibling();
sib.child_id = id;
return View(sib);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "sibling_id,child_id,age,gender")] sibling sibling)
{
if (ModelState.IsValid)
{
db.siblings.Add(sibling);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.child_id = new SelectList(db.children, "child_id", "last_name", sibling.child_id);
return View(sibling);
}
This is my Create.cshtml for Sibling:
#model dummyApp.Schema.TestModels.sibling
#{
ViewBag.Title = "Create";
}
#section Scripts{
<script type="text/javascript">
//Coding
$("#numBox").change(function () {
var htmlString = "";
var len = $(this).val();
for (var i = 0; i < len; i++) {
htmlString += ' <div class="form-group">\
#Html.LabelFor(model => model.child_id, "child_id", htmlAttributes: new { #class = "control-label col-md-2" })\
<div class="col-md-10">\
#Html.EditorFor(model => model.child_id, new { htmlAttributes = new { #class = "form-control" }})\
#Html.ValidationMessageFor(model => model.child_id, "", new { #class = "text-danger" })\
</div>\
</div>\
<div class="form-group">\
#Html.LabelFor(model => model.age, htmlAttributes: new { #class = "control-label col-md-2" })\
<div class="col-md-10">\
#Html.EditorFor(model => model.age, new { htmlAttributes = new { #class = "form-control" } })\
#Html.ValidationMessageFor(model => model.age, "", new { #class = "text-danger" })\
</div>\
</div>\
<div class="form-group">\
#Html.LabelFor(model => model.gender, htmlAttributes: new { #class = "control-label col-md-2" })\
<div class="col-md-10">\
#Html.EditorFor(model => model.gender, new { htmlAttributes = new { #class = "form-control" } })\
#Html.ValidationMessageFor(model => model.gender, "", new { #class = "text-danger" })\
</div>\
</div>\
';
}
$("#adtnl_fields").html(htmlString);
})
</script>
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>sibling</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<!--
<div class="form-group">
#Html.LabelFor(model => model.sibling_id, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.sibling_id, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.sibling_id, "", new { #class = "text-danger" })
</div>
</div>
-->
<div class="form-group">
#Html.Label("Number of Siblings:", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="number" id="numBox" class="form-control"/>
</div>
</div>
<!--
<div class="form-group">
#Html.LabelFor(model => model.child_id, "child_id", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*Html.DropDownList("child_id", null, htmlAttributes: new { #class = "form-control" })*#
#Html.EditorFor(model => model.child_id, new { htmlAttributes = new { #class = "form-control" }})
#Html.ValidationMessageFor(model => model.child_id, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.age, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.age, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.age, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.gender, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.gender, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.gender, "", new { #class = "text-danger" })
</div>
</div>
-->
<!-- Div for additional fields -->
<div id="adtnl_fields">
</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>
#Html.ActionLink("Back to List", "Index")
</div>
This is my 'sibling.cs':
public partial class sibling
{
public int sibling_id { get; set; }
public int child_id { get; set; }
public Nullable<int> age { get; set; }
public string gender { get; set; }
public virtual child child { get; set; }
}
Please help. Thank you!
You can use AddRange method in EF-6
IList<Student> newStudents = new List<Student>();
newStudents.Add(new Student() { StudentName = "Student1 by addrange" });
newStudents.Add(new Student() { StudentName = "Student2 by addrange" });
newStudents.Add(new Student() { StudentName = "Student3 by addrange" });
using (var context = new SchoolDBEntities())
{
context.Students.AddRange(newStudents);
context.SaveChanges();
}
We've got a page which currently contains a four or five partial views, but is something that could grow. At the moment, there's two POST actions, for two entirely different database functions.
If we try doing the create function on another, the redirect then results in an "Object reference not set to an instance of an object." error, which is then relating to the other POST partial view.
Is there a way to stop this? Essentially, it seems to me that the post for one partial view is trying to interact with the other. Any ideas?
Thanks
Bulletins Controller for Creating:
[HttpPost]
public ActionResult CreateMain(BulletinsViewModel viewModel)
{
if (ModelState.IsValid)
{
BulletinsContext.tblBulletins.Add(new tblBulletin
{
ID = viewModel.BulletinID,
BulletinDisplayDate = viewModel.BulletinDisplayDate,
BulletinFilename = viewModel.MainBulletinName,
IsSixthForm = viewModel.IsSixthForm
});
//For loop to delete bulletins
//If bulletin folder has more than 10 files in
//Delete the oldest file, itererate till only 10 remain
{
DirectoryInfo dir = new DirectoryInfo(#"D:\Inetpub\WWWroot\intranet\Dashboard\Dashboard\Files\Bulletins");
List<FileInfo> filePaths = dir.GetFiles().OrderByDescending(p => p.CreationTime).ToList();
for (int index = filePaths.Count() - 1; index > 9; index--)
{
var fileNames = filePaths[index].Name;
//Delete from directory
filePaths[index].Delete();
//Remove from collection to restart the loop
filePaths.RemoveAt(index);
}
}
//Save changes to database
BulletinsContext.SaveChanges();
//Return to main bulletins index page
return RedirectToAction("~/Home/Index");
}
return View(viewModel);
}
Bulletins Create View:
#model Dashboard.Viewmodels.BulletinsViewModel
#{
ViewBag.Title = "Create";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.BulletinDisplayDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BulletinDisplayDate, new { htmlAttributes = new { #class = "form-control", #id = "datepicker-basic", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.BulletinDisplayDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.MainBulletinName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="input-group">
#Html.EditorFor(model => model.MainBulletinName, new { htmlAttributes = new { #class = "form-control", #Value = "Select File...", #readonly="readonly" } })
<span class="input-group-addon" href="javascript:;" onclick="moxman.browse({ fields: 'MainBulletinName', extensions: 'pdf', path: 'D:/Inetpub/WWWroot/intranet/Dashboard/Dashboard/Files/Bulletins' });" style="cursor: pointer;"><i class="fa fa-upload"></i></span>
#Html.ValidationMessageFor(model => model.MainBulletinName, "", new { #class = "text-danger" })
</div>
</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>
}
<script type="text/javascript" src="~/Scripts/tinymce/plugins/moxiemanager/js/moxman.loader.min.js"></script>
Printer Credits Create Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult PrinterCredits(PrinterCreditsViewModel viewModel)
{
if (ModelState.IsValid)
{
//Send the email if credits are added..
//Create a bunch of variables for the email
//Create the email body etc
var fromAddress = "";
string toName = Request.Form["Username"].ToUpper();
string AmountOfCredits = Request.Form["AmountAdded"];
string Plural = "";
string Title = "";
string AddedByWho = User.Identity.Name.Split('\\')[1];
System.DateTime AddedWhen = DateTime.Now;
if (AmountOfCredits == "1")
{
Plural = " printer credit has ";
Title = "Printer Credit Added!";
}
else
{
Plural = " printer credits have ";
Title = "Printer Credits Added!";
}
var toEmail = toName + "";
var subject = AmountOfCredits + Plural + "been added to your account, " + toName;
string body = "";
//Create an SMTP client for sending an email
var smtp = new SmtpClient
{
Host = "",
Port = 25,
EnableSsl = false,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = true,
};
//Populate the SMTP client and encode the body for the HTML
using (var message = new MailMessage(fromAddress, toEmail)
{
Subject = subject,
Body = body,
IsBodyHtml = true,
BodyEncoding = System.Text.Encoding.UTF8
})
//Try to send the email. If sent, insert data.
//Redirect back to original page
//Take current printer credit from and update with fund + cost
try
{
//Link the viewmodel and the database together
PartialViewContext.tblPrinterCredits.Add(new tblPrinterCredit
{
Username = viewModel.Username,
AmountAdded = viewModel.AmountAdded,
AddedBy = AddedByWho,
AddedWhen = viewModel.AddedWhen,
Money = viewModel.AmountAdded * 0.02
});
Nullable<double> cost = viewModel.AmountAdded * 0.02;
//Update the printer credit fund and insert into tblOption
tblOption fund = (
from n in PartialViewContext.tblOptions
where n.ID == 1
select n).First();
fund.PrinterCreditFund = fund.PrinterCreditFund + cost;
PartialViewContext.SaveChanges();
message.CC.Add("");
smtp.Send(message);
Response.Redirect("~/Home/Index");
}
//If it fails, go chicken oriental (only a redirect, will eventually become a crazy message)
catch
{
smtp.Send(message);
Response.Redirect("~/Home/Index");
}
}
return View(viewModel);
Printer Credits View:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="panel">
<div class="panel-heading">
<span class="panel-icon">
<i class="fa fa-print"></i>
</span>
Add Printer Credits - #Costings
</div>
<div class="panel-body">
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<label class="control-label col-md-3">User:</label>
<div class="col-xs-8">
#Html.EditorFor(model => model.Username, new { htmlAttributes = new { #class = "form-control", #id = "Username", #name = "Username", #maxlength = "6" } })
#Html.ValidationMessageFor(model => model.Username, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Amount:</label>
<div class="col-xs-8">
#Html.EditorFor(model => model.AmountAdded, new { htmlAttributes = new { #class = "form-control", #id = "AmountAdded", #onkeyup = "Update()", #Value = 0 } })
#Html.ValidationMessageFor(model => model.AmountAdded, "", new { #class = "text-danger", #type="number" })
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Cost:</label>
<div class="col-xs-8">
#Html.EditorFor(model => model.TotalCost, new { htmlAttributes = new { #class = "form-control", #id = "TotalCost", #readonly = "readonly", #Value = "0" } })
#Html.ValidationMessageFor(model => model.TotalCost, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-1 col-md-10">
<input type="submit" value="Add Printer Credits" class="btn btn-primary btn-gradient dark btn-block" />
#Html.EditorFor(model => model.AddedBy, new { htmlAttributes = new { #class = "form-control", #Value = User.Identity.Name.Split('\\')[1], #Style = "display: none;" } })
#Html.ValidationMessageFor(model => model.AddedBy, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
</div>
}
<script type="text/javascript">
$(document).ready(
function () {
Update();
$('#AmountAdded, #TotalCost')
.keyup(function () {
Update();
})
}
);
function Update() {
var cost = 2
var one = $('#AmountAdded'),
two = $('#TotalCost');
two.val(parseInt(one.val()) * cost / 100);
}
</script>
<script type="text/javascript">
document.getElementById('Username').focus()
</script>
Just figured out that I need to tell the form which action and controller to use, despite the fact two different controllers are running the views. But anyway, an example is:
#using (Html.BeginForm("CreateMain", "Bulletins", FormMethod.Post, new { }))