Email Attachment ASP.Net MVC 5 not attaching - asp.net

I don't receive any errors, and the message itself is received. The attachment isn't included.
I do not program for the website often. The company asked me to add this and this is far as I've come via other guides. Any information is appreciated!
Index.cshtml:
#using (Html.BeginForm())
{
//Captcha authentication
#Html.AntiForgeryToken()
//Form entry field validation
#Html.ValidationSummary(true)
<div class="row">
<div class="form-group col-lg-4">
#Html.LabelFor(model => model.Name, "Name")<br />
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="form-group col-lg-4">
#Html.LabelFor(model => model.Email, "Email Address")<br />
#Html.EditorFor(model => model.Email)
#Html.ValidationMessageFor(model => model.Email)
</div>
<div class="form-group col-lg-4">
#Html.LabelFor(model => model.Telephone, "Phone Number")<br />
#Html.EditorFor(model => model.Telephone)
#Html.ValidationMessageFor(model => model.Telephone)
</div>
<div class="clearfix"></div>
<div class="form-group col-lg-12">
#Html.LabelFor(model => model.Comment, "Message")<br />
#Html.TextAreaFor(model => model.Comment, new { #class = "text-boxMessage" })
#Html.ValidationMessageFor(model => model.Comment)
</div>
<div class="form-group col-lg-4">
<input type="file" name="fileUploader"/>
</div>
</div>
<div class="row">
<div class="g-recaptcha" data-sitekey="6Lcvzo0UAAAAAAdAu2zUmDIODBEDTsDvzmgANNdb"></div>
<div class="form-group col-lg-12">
<input class="btn btn-default" type="submit" value="Submit" />
</div>
</div>
}
The method:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace Mvc4ContactForm.Models
{
public class ContactModels
{
[Required(ErrorMessage="*Required")]
public string Name { get; set; }
[Required(ErrorMessage= "*Required")]
[RegularExpression(#"^[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$", ErrorMessage = "Invalid email")]
public string Email { get; set; }
[Required(ErrorMessage = "*Required")]
public string Telephone { get; set; }
[Required(ErrorMessage= "*Required")]
public string Comment { get; set; }
public HttpPostedFileBase FileUploader { get; set; }
}
}
The controller:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using Mvc4ContactForm.Models;
namespace correinc.Controllers
{
public class ContactController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
//For captcha
[ValidateAntiForgeryToken]
public ActionResult Index(ContactModels c)
{
if (ModelState.IsValid)
{
//For captcha
CaptchaResponse response = ValidateCaptcha(Request["g-recaptcha-response"]);
if (response.Success && ModelState.IsValid)
{
//For data to smtp
try
{
MailMessage msg = new MailMessage();
SmtpClient client = new SmtpClient();
MailAddress from = new MailAddress(c.Email.ToString());
System.Text.StringBuilder sb = new System.Text.StringBuilder();
msg.IsBodyHtml = false;
client.Host = "smtp.gmail.com";
client.Port = 587;
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Credentials = new System.Net.NetworkCredential("a#b.com", "password");
msg.To.Add("b#b.com");
msg.From = from;
msg.Subject = "Website Contact Form";
sb.Append("Name: " + c.Name);
sb.Append(Environment.NewLine);
sb.Append("Email: " + c.Email);
sb.Append(Environment.NewLine);
sb.Append("Telephone: " + c.Telephone);
sb.Append(Environment.NewLine);
sb.Append("Comments: " + c.Comment);
//Fileuploader
if (c.FileUploader != null)
{
string fileName = Path.GetFileName(c.FileUploader.FileName);
msg.Attachments.Add(new Attachment(c.FileUploader.InputStream, fileName));
}
msg.IsBodyHtml = false;
msg.Body = sb.ToString();
client.Send(msg);
msg.Dispose();
return View("Success");
}
catch (Exception)
{
return View("Error");
}
}
//Captcha
else
{
return Content("Error From Google ReCaptcha : " + response.ErrorMessage[0].ToString());
}
}
return View();
}
//Captcha
public class CaptchaResponse
{
[JsonProperty("success")]
public bool Success
{
get;
set;
}
[JsonProperty("error-codes")]
public List<string> ErrorMessage
{
get;
set;
}
}
public static CaptchaResponse ValidateCaptcha(string response)
{
string secret = System.Web.Configuration.WebConfigurationManager.AppSettings["recaptchaPrivateKey"];
var client = new System.Net.WebClient();
var jsonResult = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, response));
return JsonConvert.DeserializeObject<CaptchaResponse>(jsonResult.ToString());
}
}
}

You have to set the enctype to the form property for the file uploads.
Please use the following
#using (Html.BeginForm("Index", "Contact", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
....
....
}
Please see the similar discussion in this SO thread.

Related

ArgumentNullException on MVC5 DropdownListFor

I just started learning Asp.net MVC5 and I'm getting a ArgumentNullException on the following line.
#Html.DropDownListFor(m => m.Customer.MembershipTypeId, new SelectList(Model.MembershipTypes, "Id", "Name"), "", new { #class = "form-control" })
I'm following a tutorial and I have it the exact same so I'm not sure why it's throwing this error.
I looked over the models and table data and they are populated.
Let me know if any additional info is needed to figure out this issue.
New.cshtml
#model Vidly6.VIewModel.NewCustomerViewModel
#{
ViewBag.Title = "New";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>New Customer</h2>
#using (Html.BeginForm("Create", "Customers"))
{
<div class="form-group">
#Html.LabelFor(m => m.Customer.Name)
#Html.TextBoxFor(m => m.Customer.Name, new {#class = "form-control"})
</div>
<div class="form-group">
#Html.LabelFor(m => m.Customer.BirthDate)
#Html.TextBoxFor(m => m.Customer.BirthDate, new {#class = "form-control"})
</div>
<div class="checkbox">
<label>
#Html.CheckBoxFor(m=>m.Customer.IsSubscribedToNewsletter) Subscribed to Newsletter?
</label>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Customer.MembershipTypeId)
#Html.DropDownListFor(m => m.Customer.MembershipTypeId, new SelectList(Model.MembershipTypes, "Id", "Name"), "", new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Customer.MembershipTypeId)
</div>
}
NewCustomerViewModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Vidly6.Models;
namespace Vidly6.VIewModel
{
public class NewCustomerViewModel
{
public IEnumerable<MembershipTypes> MembershipTypes { get; set; }
public Customers Customer { get; set; }
}
}
CustomersController
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Vidly6.Models;
using Vidly6.VIewModel;
namespace Vidly6.Controllers
{
public class CustomersController : Controller
{
private ApplicationDbContext _context;
public CustomersController()
{
_context = new ApplicationDbContext();
// GET: Customers
}
protected override void Dispose(bool disposing)
{
_context.Dispose();
}
public ActionResult New()
{
var membershipTypes = _context.MembershipTypes.ToList();
var viewModel = new NewCustomerViewModel();
return View(viewModel);
}
public ViewResult CustomerGoesHere()
{
var customers = _context.Customers.Include(c => c.MembershipTypes).ToList();
return View(customers);
}
public ActionResult Details(int id)
{
var customer = _context.Customers.SingleOrDefault(c => c.Id == id);
if (customer == null)
return HttpNotFound();
return View(customer);
}
}
}
MembershipTypes Table
public ActionResult New()
{
var membershipTypes = _context.MembershipTypes.ToList();
var viewModel = new NewCustomerViewModel();
return View(viewModel);
}
You don't actually use membershipTypes. You need to set the property on the viewModel otherwise it will be null.

Couldn't bind properly from view to model using BeginCollectionItem with nested collection

I am following this blog Editing a variable length list, ASP.NET MVC 2-style by Steven Anderson and started using Html.BeginCollectionItem() for my ASP.NET MVC project.
The project is about associating multiple permissions to roles. It will have a Role page(view) where user will have option to add permissions by selecting one of the permissions from drop-down list. User will also be able to add these permissions drop-down list by clicking on 'Add' button. 'Add' would dynamically add new drop-down list control on the page. Remove would remove the last drop-down list.
The issue I am facing is with binding nested collection. I have used RolePermissions list below which inturn is a list of RolePermissionViewModel.
See below for screenshots.
Role Controller: I have hardcoded sample data for testing.
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using MUtilities.Model.Entities;
using MUtilities.Web.Areas.Admin.Models;
using MUtilities.Web.Controllers;
using HtmlHelpers.BeginCollectionItem;
namespace MUtilities.Web.Areas.Admin.Controllers
{
public class RoleController : BaseController
{
public ActionResult Index()
{
return View();
}
public ViewResult BlankPermission()
{
return View("_PermissionPartial", GetPermissions());
}
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var role = MRepository.AllRoles.Find(id);
if (role == null)
{
return HttpNotFound();
}
return View(role);
}
private List<List<RolePermissionViewModel>> GetPermissionList() {
var rolePermissions = new List<List<RolePermissionViewModel>>();
rolePermissions.Add(GetPermissions());
rolePermissions.Add(GetPermissions());
return rolePermissions;
}
private List<RolePermissionViewModel> GetPermissions()
{
var permissions = new List<RolePermissionViewModel>();
permissions.Add(new RolePermissionViewModel
{
PermissionId = -1,
PermissionName = "--Select a Permission--"
});
permissions.Add(new RolePermissionViewModel
{
PermissionId = 1,
PermissionName = "Create of Utility1"
});
permissions.Add(new RolePermissionViewModel
{
PermissionId = 2,
PermissionName = "Update of of Utility1"
});
return permissions;
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,Description,RolePermissions")] RoleViewModel roleModel)
{
if (ModelState.IsValid)
{
var role = new Role();
role.Name = roleModel.Name;
//some logic here
return RedirectToAction("Index");
}
return View();
}
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//some logic to edit view
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Name,Permissions")] RoleViewModel roleModel)
{
if (ModelState.IsValid)
{
var role = MRepository.AllRoles.First(r => r.Id == roleModel.Id);
role.Name = roleModel.Name;
//some logic to commit
return RedirectToAction("Index");
}
return View();
}
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Role role = MRepository.AllRoles.Find(id);
if (role == null)
{
return HttpNotFound();
}
return View(role);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
var role = MRepository.AllRoles.Find(id);
MRepositoryAllRoles.Remove(role);
MRepository.Commit();
return RedirectToAction("Index");
}
}
}
Role View:
#model MUtilities.Web.Areas.Admin.Models.RoleViewModel
#{
ViewBag.Title = "Create";
}
#section scripts{
<script type="text/javascript">
$(function () {
$("#addPermissionBtn").click(function () {
$.ajax({
url: this.href,
cache: false,
success: function (html) {
$("#addPermissionDdl").append(html);
//The call to Sys.Mvc.FormContext._Application_Load() refreshes
//the validation on the page to include the new fields.
Sys.Mvc.FormContext._Application_Load();
}
});
return false;
});
$("#deletePermissionBtn").on("click", function () {
var pDdls = $("select[id$='__PermissionList']");
if (pDdls && pDdls.length > 1) {
pDdls.last().remove();
//$(this).parents("div.addPermissionDdl:last").remove();
}
return false;
});
});
</script>
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Role</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.RolePermissions, htmlAttributes: new { #class = "control-label col-md-2" })
#using (Html.BeginForm())
{
<div id="addPermissionDdl" class="col-md-10">
#foreach (var rolePermission in Model.RolePermissions)
{
Html.RenderPartial("_PermissionPartial", rolePermission);
}
</div>
<div class="col-md-10">
#Html.ActionLink("Add", "BlankPermission", null, new { id = "addPermissionBtn", #class = "glyphicon glyphicon-plus-sign" })
Delete
</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>
RoleViewModel: RolePermissions is a list of RolePermissionViewModel list.
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace MUtilities.Web.Areas.Admin.Models
{
public class RoleViewModel
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string Description { get; set; }
[Display(Name="Permissions")]
public List<List<RolePermissionViewModel>> RolePermissions { get; set; }
}
public class RolePermissionViewModel
{
public int PermissionId { get; set; }
public string PermissionName { get; set; }
}
}
_PermissionPartial.cshtml
#{
Layout = null;
}
#using HtmlHelpers.BeginCollectionItem;
#model IEnumerable<MUtilities.Web.Areas.Admin.Models.RolePermissionViewModel>
#using (Html.BeginCollectionItem("RolePermissions"))
{
var permissionDdl = new SelectList(Model.Select(m => m), "PermissionId", "PermissionName", "--Select a Permission--");
#Html.DropDownList("PermissionList", permissionDdl, new { #class = "form-control" });
}
But when I click Create button Name, Description would bind ok but not the Permissions. See below.
Any idea what might be happening?

asp.net mvc model didn't receive on form submit

I have written an asp.net mvc site that works fine on local.
But after publishing it, i have some problems with models sent from forms.
i think it determines my model state always not valid.
i don't receive any data!
[HttpGet]
public ActionResult LogIn()
{
return View();
}
[HttpPost]
public ActionResult LogIn(Models.LoginViewModel data)
{
if (!ModelState.IsValid)
{
return LogIn();
}
TAPortalEntities db = new TAPortalEntities();
UserAccount probableUser = db.UserAccounts.FirstOrDefault(p => p.UserName == data.UserName && p.Pass == data.Pass);
if (probableUser == null)
{
ModelState.AddModelError(string.Empty, "نام کابری یا رمز عبور اشتباه وارد شده است!");
return LogIn();
}
Session["LogedIn"] = true;
Session["UserName"] = probableUser.UserName;
Session["Course"] = probableUser.Course.Name;
Session["TeacherName"] = probableUser.Course.TeacherName;
Session["RealName"] = probableUser.RealName;
return RedirectToAction("Index", "Home");
}
and the view is like this:
#model TAPortal.Models.LoginViewModel
#{
ViewBag.Title = "ورود به سایت";
}
<h2>ورود</h2>
#using (Html.BeginForm())
{
#*#Html.AntiForgeryToken()*#
<div class="form-horizontal">
<h4>اطلاعات ورود را وارد کنید</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.UserName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserName)
#Html.ValidationMessageFor(model => model.UserName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Pass, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Pass)
#Html.ValidationMessageFor(model => model.Pass)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="ورود" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("برگشت به خانه", "Index","Home")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
and the model class :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace TAPortal.Models
{
public class LoginViewModel
{
[Required(ErrorMessage="نام کاربری باید وارد شود!")]
[Display(Name="نام کاربری")]
public string UserName { get; set; }
[Required(ErrorMessage = "رمز عبور باید وارد شود!")]
[Display(Name = "رمز عبور")]
public string Pass { get; set; }
}
}
see these results:
input:
output local :
output on online host :
Try to add this filter
[ValidateAntiForgeryToken]
to your POST Action
Edit:
in your get method instantiate your model and set to false the ValidationSummary
[HttpGet]
public ActionResult LogIn()
{
var model = new LoginViewModel();
return View(model);
}
Now I have the answer. I share it for the others who face this problem.
From first, every thing was correct but the wrong thing was the version of the .NET framework of my host. This type of coding requires .NET framework 4.5 but my host's .NET framework version was 4.0 and it was all the story.
Now I have transferred my code to a host of 4.5.

Asp.net mvc Edit Page what can I use besides .Entry?

I adding an admin area to an Asp.net MVC4 Application and I would consider myself a entry-level developer. My edit [HttpGet] action is working fine as it returns the values of asset. I have poured through a bunch of MVC4 specials online and most of them use the following for [HttpPost] Edit method:
[HttpPost]
public ActionResult Edit(ITTESI.AssetTracker.Web.UI.ViewModels.AssetDetailsViewModel models)
{
try
{
if (ModelState.IsValid)
{
_entities.Entry(models).State = EntityState.Modified;
_entities.SaveChanges();
return RedirectToAction("Index", new { ID = models.ID });
}
}
catch (DataException)
{
ModelState.AddModelError("", "Unable able to save changes....epic fail!!!");
}
return View(models);
}
The problem is that I do not have access to use .Entry in the following:
_entities.Entry(models).State = EntityState.Modified;
I am obviously missing a reference that will enable me to use it, but I am not sure what it is.
Here is my ViewModel(I would have used DbContext, but they did not):
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using ITTESI.AssetTracker.Web.UI.Content.Classes;
namespace ITTESI.AssetTracker.Web.UI.ViewModels
{
public class AssetDetailsViewModel
{
public int ID { get; set; }
public string AssetIdentifier { get; set; }
public string ManufacturerName { get; set; }
public string Model { get; set; }
public string SchoolLocation { get; set; }
public string Status { get; set; }
public string Condition { get; set; }
// [DataType(DataType.MultilineText)]
public string Notes { get; set; }
public Utils.AssignReturn AssignReturnEligible { get; set; }
public string SchoolLocationCd { get; set; }
public string SchoolLocationDisplayValue { get; set; }
public AssignedUserViewModel AssignedUserViewModelObj { get; set; }
}
}
Here is my Admin Controller:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Metadata.Edm;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using ITTESI.AssetTracker.Data.EntityModel.Entity;
using ITTESI.AssetTracker.Data.EntityModel.Definition;
using System.Data.Entity;
using ITTESI.AssetTracker.Web.UI;
using ITTESI.AssetTracker.Web.UI.Content;
using ITTESI.AssetTracker.Web.UI.Content.Classes;
using ITTESI.AssetTracker.Web.UI.ViewModelBuilders;
using ITTESI.AssetTracker.Web.UI.ViewModels;
namespace ITTESI.AssetTracker.Web.UI.Controllers
{
public class AdminController : Controller
{
ExtendedITTESI_AssetTrackerEntities _entities = new ExtendedITTESI_AssetTrackerEntities();
public ActionResult Index(ViewModels.AssetDetailsViewModel assetDetails)
{
ViewBag.PageTitle = "Admin Search";
ViewBag.HideShowLocation = "hide";
ViewBag.SubmitButtonValue = "Search";
return View("Index", assetDetails);
}
[HttpGet]
public ActionResult Edit(ITTESI_AssetTracker_Asset asset) // 'ITTESI.AssetTracker.Web.UI.ViewModels.AssetDetailsViewModel'
{
ViewBag.PageTitle = "Edit Asset";
ViewBag.SubmitButtonValue = "Save";
ViewBag.ShowLocation = true;
var model = _entities.ITTESI_AssetTracker_Asset.FirstOrDefault();
return View(model);
}
[HttpPost]
//public ActionResult Edit(ExtendedITTESI_AssetTrackerEntities ate)
public ActionResult Edit(ITTESI.AssetTracker.Web.UI.ViewModels.AssetDetailsViewModel models)
{
try
{
if (ModelState.IsValid)
{
_entities.Entry(models).State = EntityState.Modified;
_entities.SaveChanges();
return RedirectToAction("Index", new { ID = models.ID });
}
}
catch (DataException)
{
ModelState.AddModelError("", "Unable able to save changes....epic fail!!!");
}
return View(models);
}
}
}
Here is my Edit View:
#model ITTESI.AssetTracker.Data.EntityModel.Entity.ITTESI_AssetTracker_Asset
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>ITTESI_AssetTracker_Asset</legend>
#Html.HiddenFor(model => model.ID)
<div class="editor-label">
#Html.LabelFor(model => model.AssetIdentifier)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.AssetIdentifier)
#Html.ValidationMessageFor(model => model.AssetIdentifier)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AssetConditionID)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.AssetConditionID)
#Html.ValidationMessageFor(model => model.AssetConditionID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.SchoolID)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.SchoolID)
#Html.ValidationMessageFor(model => model.SchoolID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AssetCategoryID)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.AssetCategoryID)
#Html.ValidationMessageFor(model => model.AssetCategoryID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.VendorID)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.VendorID)
#Html.ValidationMessageFor(model => model.VendorID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AssignedPersonID)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.AssignedPersonID)
#Html.ValidationMessageFor(model => model.AssignedPersonID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AssetStatusID)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.AssetStatusID)
#Html.ValidationMessageFor(model => model.AssetStatusID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ManufacturerID)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ManufacturerID)
#Html.ValidationMessageFor(model => model.ManufacturerID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ModelDetail)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ModelDetail)
#Html.ValidationMessageFor(model => model.ModelDetail)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.CreatedOn)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.CreatedOn)
#Html.ValidationMessageFor(model => model.CreatedOn)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.CreatedByIdentifier)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.CreatedByIdentifier)
#Html.ValidationMessageFor(model => model.CreatedByIdentifier)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ModifiedOn)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ModifiedOn)
#Html.ValidationMessageFor(model => model.ModifiedOn)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ModifiedByIdentifier)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ModifiedByIdentifier)
#Html.ValidationMessageFor(model => model.ModifiedByIdentifier)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Notes)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Notes)
#Html.ValidationMessageFor(model => model.Notes)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
I also certain the problem is that DbContext for ExtendedITTESI_AssetTrackerEntities does not exist and after research a bit more that is part of the System.Data.Entity. The only code I have for ExtendedITTESI_AssetTrackerEntities is:
using System;
using Common.Logging;
using EFCachingProvider;
using EFCachingProvider.Caching;
using EFProviderWrapperToolkit;
using EFTracingProvider;
using ITTESI.AssetTracker.Data.EntityModel.Entity;
namespace ITTESI.AssetTracker.Data.EntityModel.Definition
{
public class ExtendedITTESI_AssetTrackerEntities : ITTESI_AssetTrackerEntities
{
private ILog logOutput;
public ExtendedITTESI_AssetTrackerEntities()
: this("name=ITTESI_AssetTrackerEntities")
{
}
public ExtendedITTESI_AssetTrackerEntities(string connectionString)
: base(EntityConnectionWrapperUtils.CreateEntityConnectionWithWrappers(
connectionString,
"EFTracingProvider",
"EFCachingProvider"
))
{
CachingPolicy = AssetTrackerEntitiesCachingPolicy.CachingPolicy();
Cache = AssetTrackerEntitiesCache.Cache();
}
#region Tracing Extensions
private EFTracingConnection TracingConnection
{
get { return this.UnwrapConnection<EFTracingConnection>(); }
}
public event EventHandler<CommandExecutionEventArgs> CommandExecuting
{
add { this.TracingConnection.CommandExecuting += value; }
remove { this.TracingConnection.CommandExecuting -= value; }
}
public event EventHandler<CommandExecutionEventArgs> CommandFinished
{
add { this.TracingConnection.CommandFinished += value; }
remove { this.TracingConnection.CommandFinished -= value; }
}
public event EventHandler<CommandExecutionEventArgs> CommandFailed
{
add { this.TracingConnection.CommandFailed += value; }
remove { this.TracingConnection.CommandFailed -= value; }
}
private void AppendToLog(object sender, CommandExecutionEventArgs e)
{
if (this.logOutput != null)
{
this.logOutput.Debug(e.ToTraceString().TrimEnd());
}
}
public ILog Log
{
get { return this.logOutput; }
set
{
if ((this.logOutput != null) != (value != null))
{
if (value == null)
{
CommandExecuting -= AppendToLog;
}
else
{
CommandExecuting += AppendToLog;
}
}
this.logOutput = value;
}
}
#endregion
#region Caching Extensions
private EFCachingConnection CachingConnection
{
get { return this.UnwrapConnection<EFCachingConnection>(); }
}
public ICache Cache
{
get { return CachingConnection.Cache; }
set { CachingConnection.Cache = value; }
}
public CachingPolicy CachingPolicy
{
get { return CachingConnection.CachingPolicy; }
set { CachingConnection.CachingPolicy = value; }
}
#endregion
}
}
I might have to create a model with DbContext is that fair to say?
Can I use anything besides .Entry? I appreciate the help, but with the way the app is set up I am not sure how to properly save edits back to the database.
there is a way besides .Entry for the Edit Action. EF is very clever, you can just fetch the object by ID form the database and change all the properties manually.
Ex:
[HttpPost]
public ActionResult Edit(ITTESI.AssetTracker.Web.UI.ViewModels.AssetDetailsViewModel models)
{
try
{
if (ModelState.IsValid)
{
ITTESI.AssetTracker.Web.UI.ViewModels.AssetDetailsViewModel temp = _entities.dbname.firstOrDefault(x = > x.ID == models.ID);
temp.AssetIdentifier = models.AssetIdentifier ;
temp.ManufacturerName = models.ManufacturerName ;
.
.
.
_entities.SaveChanges();
return RedirectToAction("Index", new { ID = models.ID });
}
}
catch (DataException)
{
ModelState.AddModelError("", "Unable able to save changes....epic fail!!!");
}
return View(models);
}
EF will understand what entity you want to modify, and will update it with "_entities.saveChanges();"
I don't really know that this will work for you, but I think it's worth trying

how to disable button and Jquery code for that button - asp.net mvc-3

there seems to be another problem ..not with JQuery code but with Action controller code...
i am putting the breakspoints on controllers and start debugging the app, its straight away going to controller and trying to pass in the null values ...please have a look and let me know... thx
public class HomeController : Controller
{
//
// GET: /Home/
UsersRepository repo = new UsersRepository();
DBHelpers db = new DBHelpers();
public ActionResult Index()
{
var users = new Users();
return View(users);
}
public ContentResult CheckLogin(Users checkuser)
{
checkuser = new Users();
if (db.CheckUserLoginDetails(checkuser))
{
return Content("Login Successful:" + checkuser.Email);
}
else
{
return Content("Login UnSuccessful");
}
}
public ContentResult Register(Users userRegister)
{
userRegister = new Users();
if (db.InsertNewUSerDetails(userRegister))
{
return Content("Registration Successful : your ID is : " + userRegister.UserID);
}
else
{
return Content("There was a problem addding you, please try again");
}
}
}
=================
here is my DBHelpers class
UsersRepository db = new UsersRepository();
public bool CheckUserLoginDetails(Users user)
{
return (from u in db.EUsers where u.Email == user.Email & u.Password == user.Password select u).Any();
}
public bool InsertNewUSerDetails(Users newUser)
{
newUser = new Users();
try
{
var date = DateTime.Now.Date;
newUser.JoiningDate = date;
db.EUsers.Add(newUser);
db.SaveChanges();
return true;
}
catch (DbEntityValidationException dbEX)
{
foreach (var validationerrors in dbEX.EntityValidationErrors)
{
foreach (var valerror in validationerrors.ValidationErrors)
{
Trace.TraceInformation("Property: {0} Error: {1}", valerror.PropertyName, valerror.ErrorMessage);
}
}
return false;
}
}
}
and here is my Users class
public class Users
{
[Key]
public virtual int UserID { get; set; }
[Required(ErrorMessage="Required")]
public virtual string FirstName { get; set; }
[Required(ErrorMessage = "Required")]
public virtual string LastName { get; set; }
[Required(ErrorMessage = "Required")]
[DataType(DataType.EmailAddress)]
public virtual string Email { get; set; }
[Required(ErrorMessage = "Required")]
[DataType(DataType.Password)]
public virtual string Password { get; set; }
[DataType(DataType.Date)]
public virtual DateTime JoiningDate { get; set; }
}
==============
problem is when i try to run the application, its directly going to Register() action and passing the null values ...
please help...
=================
here is my View Code...
#model Temp1.Models.Users
#{
ViewBag.Title = "Index";
}
<script src="#Url.Content("~/Scripts/jquery-1.5.1.js") type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-1.5.1-vsdoc.js") type="text/javascript"></script>
#using (Html.BeginForm())
{
<fieldset>
<div id="divLoginInfo">
<p>if not registered, please #Html.ActionLink("Register", "Register", "Home", new { #id = "lnkRegister" })</p>
#Html.TextBoxFor(model => model.Email, new { #class = "text" })
<br />
#Html.PasswordFor(model => model.Password, new { #class = "text" })
<p>
<input type="button" value="Login" id="btnLogin" />
</p>
<div id="Result">
<div class="Loading" style="display:none;"> Checking....</div>
</div>
</div>
</fieldset>
<br />
<div id="divRegisterInfo" style="display:none;">
<fieldset>
<legend>Users</legend>
<div class="editor-label">
#Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.LastName)
#Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Email)
#Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Password)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Password)
#Html.ValidationMessageFor(model => model.Password)
</div>
<p>
<input type="button" value="Create" id="btnRegister" />
</p>
<p>
<div id="divShowRegistrationMessage">
</div>
</p>
</fieldset>
</div>
}
<script type="text/javascript">
$('#btnLogin').click(function (e) {
var email = $('#Email').val();
var Password = $('#Password').val();
var postdata =
{
"Email": email,
"Password": Password
};
$('.Loading').fadeIn(50);
$.ajax({
url: '#Url.Action("CheckLogin","Home")',
data: postdata,
success: function (msg) {
var data = msg.split(':');
$('#Result').html(data[0]);
$('.Loading').fadeOut(50);
},
error: function (data) {
$('#Result').html(data);
$('.Loading').fadeOut(50);
}
});
e.preventDefault();
});
$('#lnkRegister').click(function (e) {
e.preventDefault();
$('#divLoginInfo').fadeOut(100);
$('#divRegisterInfo').fadeIn(100);
});
$('#btnRegister').click(function (e) {
var firstName = $('#divRegisterInfo #FirstName').val();
var lastName = $('#divRegisterInfo #LastName').val();
var email = $('#divRegisterInfo #Email').val();
var password = $('#divRegisterInfo #Password').val();
var postdata =
{
"FirstName": firstName,
"LastName": lastName,
"Email": email,
"Password": password
};
$("#divShowRegistrationMessage").html('Pleaes wait...');
e.preventDefault();
$.ajax({
type: 'POST'
url: '#Html.Action("Register","Home")',
data: postdata,
success: function (msg) {
$('#divShowRegistrationMessage').html(msg);
},
error: function (data) {
$('#divShowRegistrationMessage').html(data);
}
});
});
</script>
You have a trailing , here which might result into a javascript error:
var postdata =
{
"FirstName": firstName,
"LastName": lastName,
"Email": email,
"Password": password, // <-- remove this comma
};
The javascript error results into the next line not being executed which is e.preventDefault(); and thus the form performs a normal submit and not an AJAX submit. IIRC some browsers actually might tolerate this but others not. Anyway, it's invalid javascript and needs to be fixed.
Make sure you're attaching a different click event to each button.
If you're currently doing:
$('div').click(function(){});
Then insted you'll want to attach a different click event to each button, something like:
$('#registerButtonId').click(function(){});
$('#loginButtonId').click(function(){});

Resources