I've been trying to attach/upload multiple files in the website I'm making. The Name, Email, Subject & Message are sending but there's no attachment in the message. It seems that the files don't get in the uploads folder. I really don't know what's wrong. Please help me. I'm new with this kind of stuff. Thank you. Here's my view:
#using (Html.BeginForm("Index", "Home", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="col-md-4">
<div class="contact_form block">
<div class="row">
<div class="col-md-12 col-sm-12">
<div id="note"></div>
</div>
</div>
<div id="fields">
<div class="col-md-12 col-sm-6">
#Html.LabelFor(m => m.FromName)
#Html.TextBoxFor(m => m.FromName, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FromName)
</div>
<div class="col-md-12 col-sm-6">
#Html.LabelFor(m => m.FromEmail)
#Html.TextBoxFor(m => m.FromEmail, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FromEmail)
</div>
<div class="clear"></div>
<div class="col-md-12 col-sm-6">
#Html.LabelFor(m => m.FromSubject)
#Html.TextBoxFor(m => m.FromSubject, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FromSubject)
</div>
<div class="col-md-12">
#using (Html.BeginForm("Multiple", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div id="multiple">
<input type="file" class="multiple" name="files" multiple />
</div>
<div id="single">
<input type="file" class="single" name="files" /><br />
<input type="file" class="single" name="files" /><br />
<input type="file" class="single" name="files" /><br />
</div>
}
</div>
<div class="col-md-12">
#Html.LabelFor(m => m.Message)
#Html.TextAreaFor(m => m.Message, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Message)
</div>
<div class="col-md-12">
<div>
#if ((TempData["recaptcha"]) != null)
{
<p>#TempData["recaptcha"]</p>
}
</div>
<div class="g-recaptcha" data-sitekey="6LfVHx8TAAAAAMTDxxQrHDCxO1SyXf1GgbgNBZ5a"></div>
</div>
<div class="col-md-12"><input class="shortcode_button" type="submit" value="Send"></div>
</div>
</div>
</div>
}
And here's my controller:
public ActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Index(EmailFormModel model)
{
if (ModelState.IsValid)
{
string EncodedResponse = Request.Form["g-Recaptcha-Response"];
bool IsCaptchaValid = (ReCaptcha.Validate(EncodedResponse) == "True" ? true : false);
if(IsCaptchaValid)
{
var body = "<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>";
var message = new MailMessage();
message.To.Add(new MailAddress("***#gmail.com")); // replace with valid value
message.From = new MailAddress("***#ymailcom"); // replace with valid value
message.Subject = "Your email subject";
message.Body = string.Format(body, model.FromName, model.FromEmail, model.FromSubject, model.Message);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = "***#gmail.com", // replace with valid value
Password = "***" // replace with valid value
};
smtp.Credentials = credential;
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
await smtp.SendMailAsync(message);
//return RedirectToAction("Sent");
ViewBag.Message = "Your message has been sent!";
//TempData["message"] = "Message sent";
ModelState.Clear();
return View("Index");
}
}else
{
TempData["recaptcha"] = "Please verify that you are not a robot!";
}
}
return View(model);
}
[HttpPost]
public ActionResult Multiple(IEnumerable<HttpPostedFileBase> files)
{
foreach (var file in files)
{
if (file != null && file.ContentLength > 0)
{
file.SaveAs(Path.Combine(Server.MapPath("/uploads"), Guid.NewGuid() + Path.GetExtension(file.FileName)));
}
}
return View();
}
Your first row of code is the problem.
Html.BeginForm("Index", "Home", null, FormMethod.Post, new { enctype = "multipart/form-data"
That is a Post action to Index of your home controller. It is not possible to HttpPost another HttpPost, the action itself is expecting an HttpPost, as you can see by the data annotation above the ActionResult name
Why do you use nested forms?
Your view should not be contained nested form submissions. so reduce it to one and the same can be use to upload files.
#using (Html.BeginForm("Index", "Home", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="col-md-4">
<div class="contact_form block">
<div class="row">
<div class="col-md-12 col-sm-12">
<div id="note"></div>
</div>
</div>
<div id="fields">
<div class="col-md-12 col-sm-6">
#Html.LabelFor(m => m.FromName)
#Html.TextBoxFor(m => m.FromName, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FromName)
</div>
<div class="col-md-12 col-sm-6">
#Html.LabelFor(m => m.FromEmail)
#Html.TextBoxFor(m => m.FromEmail, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FromEmail)
</div>
<div class="clear"></div>
<div class="col-md-12 col-sm-6">
#Html.LabelFor(m => m.FromSubject)
#Html.TextBoxFor(m => m.FromSubject, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FromSubject)
</div>
<div class="col-md-12">
{
<div id="multiple">
<input type="file" class="multiple" name="files" multiple />
</div>
<div id="single">
<input type="file" class="single" name="files" /><br />
<input type="file" class="single" name="files" /><br />
<input type="file" class="single" name="files" /><br />
</div>
</div>
<div class="col-md-12">
#Html.LabelFor(m => m.Message)
#Html.TextAreaFor(m => m.Message, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Message)
</div>
<div class="col-md-12">
<div>
#if ((TempData["recaptcha"]) != null)
{
<p>#TempData["recaptcha"]</p>
}
</div>
<div class="g-recaptcha" data-sitekey="6LfVHx8TAAAAAMTDxxQrHDCxO1SyXf1GgbgNBZ5a"></div>
</div>
<div class="col-md-12"><input class="shortcode_button" type="submit" value="Send"></div>
</div>
</div>
</div>
}
Moreever add a parameter to Action to receive files from client request and process it at same action.
public async Task<ActionResult> Index(EmailFormModel model, IEnumerable<HttpPostedFileBase> files)
{
if (ModelState.IsValid)
{
//logic here upload file logic here.
foreach (var file in files)
{
if (file != null && file.ContentLength > 0)
{
file.SaveAs(Path.Combine(Server.MapPath("/uploads"), Guid.NewGuid() + Path.GetExtension(file.FileName)));
}
}
//Rest of business logic here
string EncodedResponse = Request.Form["g-Recaptcha-Response"];
bool IsCaptchaValid = (ReCaptcha.Validate(EncodedResponse) == "True" ? true : false);
if(IsCaptchaValid)
{
var body = "<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>";
var message = new MailMessage();
message.To.Add(new MailAddress("***#gmail.com")); // replace with valid value
message.From = new MailAddress("***#ymailcom"); // replace with valid value
message.Subject = "Your email subject";
message.Body = string.Format(body, model.FromName, model.FromEmail, model.FromSubject, model.Message);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = "***#gmail.com", // replace with valid value
Password = "***" // replace with valid value
};
smtp.Credentials = credential;
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
await smtp.SendMailAsync(message);
//return RedirectToAction("Sent");
ViewBag.Message = "Your message has been sent!";
//TempData["message"] = "Message sent";
ModelState.Clear();
return View("Index");
}
}else
{
TempData["recaptcha"] = "Please verify that you are not a robot!";
}
}
return View(model);
}
Related
I'm trying to call actionresult in my controller. But it doesn't call it from the view.
I have tried using onclick="location.href='#Url.Action("action", "controller")'"> but it doesn't even enter the function.
My view:
#using (Html.BeginForm("WritePost", "Post", FormMethod.Post, new { enctype
= "Multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Skriv inlägg</h4>
<hr />
<div>
#{Html.RenderAction("_CategoryPartialView", "Category");}
#Html.HiddenFor(model => model.CategoryId)
</div>
<div class="form-group">
#Html.LabelFor(model => model.Title, htmlAttributes: new { #class =
"control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Title, new { htmlAttributes = new {
#class = "form-control" } })
#Html.ValidationMessageFor(model => model.Title, "", new { #class =
"text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Content, htmlAttributes: new { #class =
"control-label col-md-2" })
<div class="col-md-10">
#Html.TextAreaFor(model => model.Content, 10, 100, new { #class =
"form-control" })
#Html.ValidationMessageFor(model => model.Content, "", new { #class =
"text-danger" })
</div>
<input type="file" name="file" />
#Html.ValidationMessageFor(model => model.File)
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Send" class="btn btn-default" />
My Controller
public ActionResult EmailWhenPost()
{
try
{
if (ModelState.IsValid)
{
var senderEmail = new MailAddress("ExampleMail#gmail.com");
var receiverEmail = new MailAddress("ExampleMail2#gmail.com");
var password = "Pass";
var subject = "New Post";
var body = "Message";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(senderEmail.Address, password)
};
using (var mess = new MailMessage(senderEmail, receiverEmail)
{
Subject = subject,
Body = body
})
{
smtp.Send(mess);
}
return View();
}
}
catch (Exception)
{
ViewBag.Error = "Some Error";
}
return View();
}
I want to use the function to send an email when a post is sent. It should not return a view, just trigger the function.
You should call the correct function MyController/EmailWhenPost (please rename this to SendEmail, and add an attribute of [HttpPost] and then in the controller action just return void (a controller method that returns void will produce an EmptyResult.)
First read this article about general rounting in ASP.NET MVC
Then read this msdn article about producing empty results
I'm following this guide here to create a step wizard to traverse multiple pages with forms on each while saving each forms data to store in my db but the problem I'm having is on the second page 'addressDetails'. When I press the prevBtn to return to the previous page 'basicDetails', my form is trying to do client side validation and I get all the validation errors instead of posting to my action method to see whether the prevBtn or nextBtn was pressed
Here is my addressDetails page
<div class="col-sm-7 col-sm-offset-1">
#using (Html.BeginForm("AddressDetails", "User", FormMethod.Post)) {
<div class="row">
<h3>What's the address for this payout method?</h3>
</div>
<div class="row">
<div class="form-group">
<label for="AddressLine1">Street address</label>
#Html.TextBoxFor(m => m.StreetAddressLine1, new { #id = "AddressLine1", #class = "form-control input-lg", placeholder = "e.g. 123 Main St." }) #Html.ValidationMessageFor(m => m.StreetAddressLine1,
"", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="form-group">
<label for="AddressLine2">Apt, suite, bldg. (optional)</label>
#Html.TextBoxFor(m => m.StreetAddressLine2, new { #id = "AddressLine2", #class = "form-control input-lg", placeholder = "e.g. Apt #6" }) #Html.ValidationMessageFor(m => m.StreetAddressLine2,
"", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-sm-6" style="padding-left: 0px; padding-right: 5px;">
<div class="form-group">
<label for="City">City</label> #Html.TextBoxFor(m => m.City, new { #id = "City", #class = "form-control input-lg" })
#Html.ValidationMessageFor(m => m.City, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-sm-6" style="padding-left: 5px; padding-right: 0px;">
<div class="form-group">
<label for="State">State / Province</label>
#Html.DropDownListFor(m => m.StateCode, new SelectList(Model.StateList, "Value", "Text"), "", new { #id = "State", #class = "btn-group-lg countryList form-control selectpicker" }) #Html.ValidationMessageFor(m
=> m.StateCode, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<label for="PostalCode">Zip code / Postal code</label>
#Html.TextBoxFor(m => m.PostalCode, new { #id = "PostalCode", #class = "form-control input-lg", placeholder = "e.g. 94102" }) #Html.ValidationMessageFor(m => m.PostalCode, "", new { #class =
"text-danger" })
</div>
</div>
<div class="row">
#Html.DropDownListFor(m => m.SelectedCountryId, new SelectList(Model.CountryList, "Value", "Text"), new { #id = "Country", #class = "btn-group-lg countryList form-control selectpicker" })
</div>
<div class="row">
<hr />
</div>
<div class="row">
<div class="col-sm-12">
<input type="submit" name="prevBtn" value='Previous' />
<input type="submit" name="nextBtn" value='Next' />
</div>
</div>
}
</div>
Here is my action method
[HttpPost]
public ActionResult AddressDetails(UserAddressViewModel addressViewModel, string prevBtn, string nextBtn)
{
YogaProfileBankAccount obj = GetBankAccount();
if (prevBtn != null)
{
UserBillingViewModel billingViewModel = new UserBillingViewModel();
//bd.CustomerID = obj.CustomerID;
//bd.CompanyName = obj.CompanyName;
return View("BasicDetails", billingViewModel);
}
if (nextBtn != null)
{
if (ModelState.IsValid)
{
//obj.Address = data.Address;
//obj.City = data.City;
//obj.Country = data.Country;
//obj.PostalCode = data.PostalCode;
return View("AccountDetails");
}
}
return View();
}
So here is what happens when I press previous, all the fields try to get validated
I have a MVC application and want to generate PDF using HTML. In here I use wkHTMLtoPdf exe to do my job.
I call to an action method from client side using jquery. Then it hit to below method.
public FileContentResult ExportInvoiceASPDF(string invno)
{
try
{
Byte[] bytes;
var fullUrl = this.Url.Action("pdfCustomerInvoice", "Report", new { invNo = invno }, Request.Url.Scheme);
bytes = WKHtmlToPdf(fullUrl);
FileContentResult result = new FileContentResult(bytes, "application/pdf")
{
FileDownloadName = "PriceNotification"
};
return File(result.FileContents, "application/pdf");
}
catch (Exception ex)
{
throw;
}
}
In here I called to WKHtmlToPdf function for getting byte stream. (Below code extracted from stackoverflow thread)
public byte[] WKHtmlToPdf(string url_input)
{
try
{
var fileName = " - ";
var wkhtmlDir = ConfigurationSettings.AppSettings["wkhtmlDir"];//Directory of wkHtmltopdf exe
var wkhtml = ConfigurationSettings.AppSettings["wkhtml"];//wkhtmltopdf exe location
var p = new Process();
url = url_input;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = wkhtml;
p.StartInfo.WorkingDirectory = wkhtmlDir;
string switches = "";
switches += "--print-media-type ";
switches += "--margin-top 10mm --margin-bottom 10mm --margin-right 10mm --margin-left 10mm ";
switches += "--page-size Letter ";
p.StartInfo.Arguments = switches + " " + url + " " + fileName;
p.Start();
//read output
byte[] buffer = new byte[32768];
byte[] file;
using (var ms = new MemoryStream())
{
while (true)
{
int read = p.StandardOutput.BaseStream.Read(buffer, 0, buffer.Length);
if (read <= 0)
{
break;
}
ms.Write(buffer, 0, read);
}
file = ms.ToArray();
}
// wait or exit
p.WaitForExit(60000);
// read the exit code, close process
int returnCode = p.ExitCode;
p.Close();
return returnCode == 0 ? file : null;
}
catch (Exception ex)
{
// set your exceptions here
return null;
}
}
Here I execute the view. (the page which I want to export as PDF)
public ActionResult pdfCustomerInvoice(string invNo)
{
var inv = _customerInvoiceService.GetCustomerInvoice(invNo);
InvoiceSummaryReportsVM invRepVM = new InvoiceSummaryReportsVM();
//My data assigning part going here
return View(invRepVM);
}
Here is pdfCustomerInvoice html.
#model Pro.Web.Models.ViewModels.InvoiceSummaryReportsVM
#{
Layout = null;
}
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="center">
<h2>Tax Invoice</h2>
</div>
<div class="row">
<br />
<br />
<br />
<br />
<br />
</div>
<div class="row">
<div class="col-md-6">
</div>
<div class="col-md-6">
<div class="row">
<div class="col-md-3">
#Html.LabelFor(model => model.InvoiceNo, htmlAttributes: new { #class = "control-label" })
</div>
<div class="col-md-3">
#Html.DisplayFor(model => model.InvoiceNo, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="row">
<div class="col-md-3">
#Html.LabelFor(model => model.InvoiceDate, htmlAttributes: new { #class = "control-label" })
</div>
<div class="col-md-3">
#Html.DisplayFor(model => model.InvoiceDate, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="row">
<div class="col-md-3">
#Html.LabelFor(model => model.AccountNo, htmlAttributes: new { #class = "control-label" })
</div>
<div class="col-md-3">
#Html.DisplayFor(model => model.AccountNo, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="row">
<div class="col-md-3">
#Html.LabelFor(model => model.InvoiceStatementPeriod, htmlAttributes: new { #class = "control-label" })
</div>
<div class="col-md-3">
#Html.DisplayFor(model => model.InvoiceStatementPeriod, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
#Html.LabelFor(model => model.OpeningBalance, htmlAttributes: new { #class = "control-label" })
</div>
<div class="col-md-6">
#Html.DisplayFor(model => model.OpeningBalance, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="row">
<div class="col-md-6">
#Html.LabelFor(model => model.InvoiceTotal, htmlAttributes: new { #class = "control-label" })
</div>
<div class="col-md-6">
#Html.DisplayFor(model => model.InvoiceTotal, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="row">
<div class="col-md-6">
#Html.LabelFor(model => model.TaxAmount, htmlAttributes: new { #class = "control-label" })
</div>
<div class="col-md-6">
#Html.DisplayFor(model => model.TaxAmount, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="row">
<div class="col-md-6">
#Html.LabelFor(model => model.TotalAmountPayable, htmlAttributes: new { #class = "control-label" })
</div>
<div class="col-md-6">
#Html.DisplayFor(model => model.TotalAmountPayable, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
</body>
</html>
The issue is when I execute the code, it is generated the PDF without styling. (All data align to left side.)
But when I call to "pdfCustomerInvoice" method directly, the html comes properly with styling.
In here I have styling issue. Please give me a direction for fixing this problem.
It seems that bootstrap won't load then.
Try to link bootstrap css from your file system.
For details: https://stackoverflow.com/a/20357784/6589639
I would like to put uploadify in the website I'm making so that I can see the progress of the files that being attach. So I search on how to do that, I know I'm doing something wrong that's why it's not working(the progress doesn't show). Please help me, I'm new with this kind of stuff. Thank you. Here's my controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Index(EmailFormModel model, IEnumerable<HttpPostedFileBase> files)
{
if (ModelState.IsValid)
{
List<string> paths = new List<string>();
foreach (var file in files)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/uploads"), fileName);
file.SaveAs(path);
paths.Add(path);
}
}
var message = new MailMessage();
foreach (var path in paths)
{
var fileInfo = new FileInfo(path);
var memoryStream = new MemoryStream();
using (var stream = fileInfo.OpenRead())
{
stream.CopyTo(memoryStream);
}
memoryStream.Position = 0;
string fileName = fileInfo.Name;
message.Attachments.Add(new Attachment(memoryStream, fileName));
}
//Rest of business logic here
string EncodedResponse = Request.Form["g-Recaptcha-Response"];
bool IsCaptchaValid = (ReCaptcha.Validate(EncodedResponse) == "True" ? true : false);
if (IsCaptchaValid)
{
var body = "<p>Email From: {0} ({1})</p><p>Subject: {2} </p><p>Message:</p><p>{3}</p>";
message.To.Add(new MailAddress("***#gmail.com")); // replace with valid value
message.From = new MailAddress("***#ymailcom"); // replace with valid value
message.Subject = "Your email subject";
message.Body = string.Format(body, model.FromName, model.FromEmail, model.FromSubject, model.Message);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = "***#gmail.com", // replace with valid value
Password = "***" // replace with valid value
};
smtp.Credentials = credential;
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
await smtp.SendMailAsync(message);
ViewBag.Message = "Your message has been sent!";
ModelState.Clear();
return View("Index");
}
}
else
{
TempData["recaptcha"] = "Please verify that you are not a robot!";
}
}
return View(model);
}
public ActionResult Upload()
{
var file = Request.Files["Filedata"];
string savePath = Server.MapPath(("~/uploads") + file.FileName);
file.SaveAs(savePath);
return Content(Url.Content(("~/uploads") + file.FileName));
}
And here's the script that I add to my _Layout.cshtml :
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery-1.10.2.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Content/UploadifyContent/jquery.uploadify.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Content/UploadifyContent/jquery.uploadify.min.js")"></script>
<link rel="stylesheet" type="text/css" href="#Url.Content("~/Content/UploadifyContent/uploadify.css")" />
<script type="text/javascript">
$(function () {
$('#file_upload').uploadify({
'swf': "#Url.Content("~/Content/UploadifyContent/uploadify.swf")",
'cancelImg': "#Url.Content("~/Content/UploadifyContent/uploadify-cancel.png")",
'uploader': "#Url.Action("Upload", "Home")",
'onUploadSuccess': function (file, data, response) {
$("#uploaded").append("<img src='" + data + "' alt='Uploaded Image' />");
}
});
});
</script>
And here's my view:
#using (Html.BeginForm("Index", "Home", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="col-md-4">
<div class="contact_form block">
<div class="row">
<div class="col-md-12 col-sm-12">
<div id="note"></div>
</div>
</div>
<div id="fields">
<div class="col-md-12 col-sm-6">
#Html.LabelFor(m => m.FromName)
#Html.TextBoxFor(m => m.FromName, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FromName, null, new { #class = "text-danger" })
</div>
<div class="col-md-12 col-sm-6">
#Html.LabelFor(m => m.FromEmail)
#Html.TextBoxFor(m => m.FromEmail, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FromEmail, null, new { #class = "text-danger" })
</div>
<div class="clear"></div>
<div class="col-md-12 col-sm-6">
#Html.LabelFor(m => m.FromSubject)
#Html.TextBoxFor(m => m.FromSubject, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FromSubject, null, new { #class = "text-danger" })
</div>
<div class="col-md-12 col-sm-6">
<form action="" method="post" enctype="multipart/form-data">
<label for="file1">Attachments</label>
<input type="file" name="files" id="file1" multiple />
</form>
<div id="uploaded"></div>
</div>
<div class="col-md-12">
#Html.LabelFor(m => m.Message)
#Html.TextAreaFor(m => m.Message, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Message, null, new { #class = "text-danger" })
</div>
<div class="col-md-12">
<div>
#if ((TempData["recaptcha"]) != null)
{
<p>#TempData["recaptcha"]</p>
}
</div>
<div class="g-recaptcha" data-sitekey="6LfVHx8TAAAAAMTDxxQrHDCxO1SyXf1GgbgNBZ5a"></div>
</div>
<div class="col-md-12"><input class="shortcode_button" type="submit" value="Send"></div>
</div>
</div>
</div>
}
I'm new to asp.net and this is my first application.
I'm developing an application that manages insurance requests. The model Request contains a file upload. the addDemand (adds a request)requires a member(adherent) to be logged in. Every time I try to run the addDemande I get the error:
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[Mutuelle.Domain.Entities.Demande]', but this dictionary requires a model item of type 'Mutuelle.Domain.Entities.Demande'.
Here's the controller:
public ActionResult AddDemande()
{
Demande demande = new Demande();
return View(demande);
}
[HttpPost]
public ActionResult AddDemande([Bind(Exclude = "fichier")]Demande demande, HttpPostedFileBase fichier)
{
try
{
if (!ModelState.IsValid)
{
return View();
}
else
{
BinaryReader fichierReader = new BinaryReader(fichier.InputStream);
byte[] fichiers = fichierReader.ReadBytes(fichier.ContentLength);
demande.fichier = fichiers;
AdherentDService adherentService = new AdherentDService();
Adherent adherent = (Adherent)Session["logedAd"];
demande.nomBeneficiaire = adherent.nom;
demande.eMailBeneficiaire = adherent.eMail;
demande.beneficiare = adherent;
adherent.listDemandes.Add(demande);
adherentService.Updateadherent(adherent);
demande.beneficiare = adherent;
adherentService.CreateaDemande(demande);
Session.Remove("logedAd");
Session.Add("logedAd", adherent);
return RedirectToAction("Demandes");
}
}
catch
{
return RedirectToAction("Index", "Home");
}
}
And here's the View:
model Mutuelle.Domain.Entities.Demande
#{
ViewBag.Title = "AddDemande";
}
<h2>AddDemande</h2>
#using (Html.BeginForm("AddDemande", "Adherent", FormMethod.Post, new { #enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Demande</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.Nomrubrique, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Nomrubrique)
#Html.ValidationMessageFor(model => model.Nomrubrique)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.fichier, new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input style="margin-left:0px;cursor:pointer;" type="file" name="fichier" id="fichier" />
</div>
</div>