controller do not hit when use AdditionalFields in remote validation - asp.net-mvc

In product class i have code properties which need to be unique. I use remote validation. but it makes problem when editing. so i add AdditionalFields. it works fine when perform edit operation but product can not create now. it never hit controller when use AdditionalFields in remote validation..
My model:
public class Product
{
public int Id { get; set; }
[Remote("IsCodeAvailable", "Product", AdditionalFields ="Id", HttpMethod = "GET", ErrorMessage = "Product Code already taken")]
public string Code { get; set; }
public string Name { get; set; }
}
here is my validation code
[HttpGet]
public JsonResult IsCodeAvailable(string code, int Id)
{
try
{
var flag = true;
if (Id == 0) // its a new object
{
flag = !db.Product.Any(x => x.Code == code);
}
else // its an existing object so exclude existing objects with the id
{
flag = !db.Product.Any(x => x.Code == code && x.Id != Id);
}
return Json(flag, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
and here is my view
<div class="form-horizontal">
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.Code, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Code, new { htmlAttributes = new { #class = "form-control", #required = "required", #style = "text-transform:uppercase" } })
#Html.ValidationMessageFor(model => model.Code, "", new { #class = "text-danger" })
</div>
</div>
<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>
Any kind of help will be greatly appreciated

Related

Another [Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Cannot perform runtime binding on a null reference'] in ASP.NET MVC

I tried to have a file upload into another folder, it works fine when it directly add to the database, but if I try to use it with MultipleDocumentCreateClass for the stored procedure, I get this error:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Cannot perform runtime binding on a null reference'
Controller
// GET: Activity/DocumentNew
public ActionResult DocumentNew(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Hoạt_động hoạt_động = db.Hoạt_động.Find(id); ;
ViewBag.act = hoạt_động;
if (hoạt_động == null)
{
return HttpNotFound();
}
MultipleDocumentCreateClass mtd = new MultipleDocumentCreateClass();
mtd.Mã_Hoạt_động = hoạt_động.Mã_Hoạt_động;
Dropdownlist2();
return View(mtd);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DocumentNew([Bind(Include = "Mã_Hoạt_động, Tên, Loại,Thông_tin, Nội_dung")]MultipleDocumentCreateClass mt)
{
if (ModelState.IsValid)
{
if (Request.Files.Count > 0)
{
HttpPostedFileBase file = Request.Files[0];
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
//Save into folder
file.SaveAs(Server.MapPath("/App_Data/Video/" + fileName));
mt.Nội_dung = "~/App_Data/Video/" + fileName;
mt.Tên = Path.GetFileNameWithoutExtension(file.FileName);
}
db.MultipleDocCr(mt.Mã_Hoạt_động, mt.Tên, mt.Loại, mt.Thông_tin, mt.Nội_dung);
db.SaveChanges();
return RedirectToAction("Index");
}
}
return View(mt);
}
MultipleDocumentUseClass:
public class MultipleDocumentCreateClass
{
public Nullable<int> Mã_Hoạt_động { get; set; }
public string Tên { get; set; }
public string Loại { get; set; }
public string Thông_tin { get; set; }
public string Nội_dung { get; set; }
}
View
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Hoạt động: #Model.Mã_Hoạt_động</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Mã_Hoạt_động, new { value = ViewBag.act.Mã_Hoạt_động })
<dt>
Hoạt động:
#ViewBag.act.Tên
</dt>
<div class="form-group">
#Html.LabelFor(model => model.Loại, "Thể loại", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Loại, new SelectList(ViewBag.doc, "Value", "Text"), new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Loại, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Thông_tin, "Thông tin", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Thông_tin, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Thông_tin, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Nội_dung, "Chọn File", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Nội_dung, new { htmlAttributes = new { Type = "file" } })
#Html.ValidationMessageFor(model => model.Nội_dung, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Lưu" class="btn btn-default" />
</div>
</div>
</div>
}
The error points to this line
#Html.HiddenFor(model => model.Mã_Hoạt_động, new { value = ViewBag.act.Mã_Hoạt_động })
but when I add value manually without uploading, it works fine.
So the answer at the #using (Html.BeginForm()) in View
Change it into this #using (Html.BeginForm("DocumentNew", "Activity", FormMethod.Post, new { enctype = "multipart/form-data" }))

Deserializing current JSON Array to perform edit operation using web api

I am using web API to edit values from collection in MongoDB.I have added code to fetch values from mongodb and have called it in another to fetch the api to perform edit functionality.
My id is getting passed to the action and still null refernce exception occur when i fix it deserialize array error occur. I tried to put deserialize the array using code found in net but it didnt work! Why does this error occur? I am new in web api and mongo db !! Please help!
Contact.cs(Model class)
public class Contact
{
[BsonId]
public string Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
}
mongodbcontroller(Controller)
[System.Web.Http.HttpPut]
public Contact Edit(Contact contact)
{
var contactsList = mongoDatabase.GetCollection("contact");
WriteConcernResult result;
bool hasError = false;
string errorMessage = string.Empty;
try
{
if (!string.IsNullOrEmpty(contact.Id))
{
IMongoQuery query = Query.EQ("Id", contact.Id);
IMongoUpdate update = MongoDB.Driver.Builders.Update
//.Set("Id",contact.Id)
.Set("Name", contact.Name)
.Set("Address", contact.Address)
.Set("Phone", contact.Phone)
.Set("Email", contact.Email);
result = contactsList.Update(query, update);
contactsList.Save(contact);
hasError = result.HasLastErrorMessage;
}
}
catch(Exception ex)
{
errorMessage = ex.ToString();
}
if (!hasError)
{
return contact;
}
else
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
}
TestController(Consuming the api)
public ActionResult Edit(string id)
{
//Contact contact = new Contact();
Contact contact = new Contact();
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:61093/api/MongoDb/edit");
//HTTP GET
var responseTask = client.GetAsync("?id=" + id);
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsAsync<Contact>();
readTask.Wait();
contact = readTask.Result;
}
}
}
catch (Exception ex)
{
}
return View(contact);
}
[HttpPost]
public ActionResult Edit(Contact contact)
{
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:61093/api/MongoDb/edit");
//HTTP GET
var putTask = client.PutAsJsonAsync<Contact>("contact",contact);
putTask.Wait();
var result = putTask.Result;
if (result.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
}
}
catch (Exception ex)
{
}
return View(contact);
}
Edit.cshtml(View)
#model TestApi.Models.Contact
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Contact</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<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.Address, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Address, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Address, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Phone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Phone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Phone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Screenshots of my code is attched below

ASP.NET MVC Route Parameter replacing Model Field

I am testing an ASP.NET MVC 5 application with Visual Studio 2017 Community edition.
I am trying to save Assort model to database with following code.
I am navigating to Assort Create page with URL /Assort/Create/1A.
The parameter 1A is needed on create page of Assort as I need to display some additional information from that parameter on create page itself.
But when I submit the data, 1A parameter value is being inserted as ID value of Assort model, and thus my ModelState is invalid and I am unable to save data.
Can anyone help me?
MODEL
public class Assort
{
[Key]
public int ID { get; set; }
[Display(Name = "Assort No")]
[Required(ErrorMessage = "Assort No can not be empty.")]
public int ASSORTNO { get; set; }
[Display(Name = "Date")]
[Required(ErrorMessage = "Date can not be empty.")]
public DateTime DATE { get; set; }
[Display(Name = "RFNO")]
[Required(ErrorMessage = "RFNO can not be empty.")]
[StringLength(50)]
public string RFNO { get; set; }
[Display(Name = "Manager")]
[Required(ErrorMessage = "Manager can not be empty.")]
public int MANAGER { get; set; }
[Display(Name = "Caret")]
[Required(ErrorMessage = "Caret can not be empty.")]
public decimal CARET { get; set; }
[Display(Name = "MFG Size")]
[Required(ErrorMessage = "MFG Size can not be empty.")]
public decimal MFGSIZE { get; set; }
[Display(Name = "Total PCS")]
[Required(ErrorMessage = "Total PCS can not be empty.")]
public decimal TOTALPCS { get; set; }
[StringLength(50)]
public string APPROVALSTATUS { get; set; }
[Display(Name = "Details")]
public string DETAILS { get; set; }
[ScaffoldColumn(false)]
public DateTime CREATE_TIMESTAMP { get; set; }
[ScaffoldColumn(false)]
public DateTime LAST_EDIT_TIMESTAMP { get; set; }
[UIHint("AssortReturn")]
public virtual List<AssortReturn> AssortReturn { get; set; }
public Assort()
{
AssortReturn = new List<AssortReturnModel.AssortReturn>();
}
[ForeignKey("RFNO")]
public virtual Rough rough { get; set; }
}
ACTION
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Assort assort)
{
if (ModelState.IsValid)
{
assort.APPROVALSTATUS = "NOT APPROVED";
assort.CREATE_TIMESTAMP = DateTime.Now;
assort.LAST_EDIT_TIMESTAMP = DateTime.Now;
db.Assorts.Add(assort);
db.SaveChanges();
return RedirectToAction("Index");
}
Initialize(assort.RFNO,"CREATE");
return View(assort);
}
VIEW
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ASSORTNO, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ASSORTNO, new { htmlAttributes = new {#readonly="readonly",#Value=ViewBag.ASSORTNO, #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ASSORTNO, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DATE, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DATE, new { htmlAttributes = new {#autofocus="autofocus",#Value=ViewBag.CURRENTDATE, #class = "form-control date" } })
#Html.ValidationMessageFor(model => model.DATE, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.RFNO, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.RFNO, new { htmlAttributes = new { #readonly = "readonly", #Value = ViewBag.RFNO, #class = "form-control" } })
#Html.TextBox("AVAILABLECARET",(decimal)ViewBag.AVAILABLECARET,new {#class="form-control txtAvailablecaret",#readonly="readonly" })
#Html.ValidationMessageFor(model => model.RFNO, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.MANAGER, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.EditorFor(model => model.MANAGER, new { htmlAttributes = new { #class = "form-control" } })*#
#Html.DropDownListFor(model => model.MANAGER, new SelectList(ViewBag.MANAGERLIST, "ID", "USERNAME"), "Select Manager", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.MANAGER, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CARET, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CARET, new { htmlAttributes = new { #class = "form-control txtCaret" } })
#Html.ValidationMessageFor(model => model.CARET, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.MFGSIZE, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MFGSIZE, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MFGSIZE, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TOTALPCS, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TOTALPCS, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TOTALPCS, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DETAILS, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DETAILS, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DETAILS, "", 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 btnCreate" />
</div>
</div>
</div>
}
This is because of the default route, which is handling your request. It looks like:
{controller}/{action}/{id}
And so A1 gets bound to ID. If you want a different behavior, say A1 is still a part of the URL, but binds to a different param, say "name", you need a new route for that:
routes.MapRoute(
name: "CreateAssort",
url: "Assort/Create/{name}",
defaults: new { controller = "Assort", action = "Create"}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Now "name" will hold A1 and not ID. Notice how your custom route comes before the default one. This is important - routing picks the first route that matches the request.
What you can do is add a hidden input field named ID to your view.
When the form will be submitted, the value from this field will take precedence over the one from your route i.e. '1A' and the model would have ID as 0 if you don't set the hidden input's value.
I had same issue. But problem is when you creating an model.
You need to have two methods.
[HttpGet] // http://localhost/Assort/Create/1
public ActionResult Create(int Id)
{
ModelState.Remove(nameof(Id)); // this will remove binding
var assort = new Assort()
{
Id = 'whatever',
....
};
return View(assort);
}
[HttpPost] // http://localhost/Assort/Create/
public ActionResult Create(Models.Assort assort)
{
if (ModelState.IsValid)
{
assort.APPROVALSTATUS = "NOT APPROVED";
assort.CREATE_TIMESTAMP = DateTime.Now;
assort.LAST_EDIT_TIMESTAMP = DateTime.Now;
db.Assorts.Add(assort);
db.SaveChanges();
return RedirectToAction("Index");
}
Initialize(assort.RFNO,"CREATE");
return View(assort);
}
C# ASP MVC Route Model ID bug

MVC Unobtrusive custom rule only works in one form on client

I built a custom validation rule for one particular field on my MVC 5 app. It works great on the edit form, but when validating that same field on the "create' form, the client side validation does not fire - The client side validation is triggered, but on the create form it shows as valid, even though I can see it is not. So no message is shown.
Both forms use the same model.
The scripts are added in the _layout page so both views have all the scripts.
Both views have the exact same razor code including the ValidationMessageFor()
When the form gets to the controller, the model is not valid due to the custom error. So the validation is working on the server side, but not the client. I can't find anything that would make it work in one form but not the other.
Here is my code:
Custom attribute:
public class AtLeastOneRequiredAttribute : ValidationAttribute, IClientValidatable
{
public string OtherPropertyNames;
public AtLeastOneRequiredAttribute(string otherPropertyNames)
{
OtherPropertyNames = otherPropertyNames;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string[] propertyNames = OtherPropertyNames.Split(',');
bool IsAllNull = true;
foreach(var i in propertyNames)
{
var p = validationContext.ObjectType.GetProperty(i);
var val = p.GetValue(validationContext.ObjectInstance, null);
if(val != null && val.ToString().Trim() != "")
{
IsAllNull = false;
break;
}
}
if(IsAllNull)
{
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
else
{
return null;
}
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rules = new ModelClientValidationRule()
{
ErrorMessage = FormatErrorMessage(metadata.DisplayName),
ValidationType = "atleastonerequired"
};
rules.ValidationParameters["otherpropertynames"] = OtherPropertyNames;
yield return rules;
}
}
Client code:
$(function() {
$.validator.unobtrusive.adapters.addSingleVal("atleastonerequired", "otherpropertynames");
$.validator.addMethod("atleastonerequired", function (value, element, params) {
var param = params.toString().split(',');
var IsAllNull = true;
$.each(param, function (i, val) {
var valueOfItem = $('#Activity_' + val).val().trim();
if (valueOfItem != '') {
IsAllNull = false;
return false;
}
});
if (IsAllNull) {
return false;
}
else {
return true;
}
})
})
View - Edit & Create Forms are identical:
#using (Html.BeginForm("Edit", "Activity", FormMethod.Post, new { #id = "editActivityForm" }))
{
#Html.AntiForgeryToken()
<div class="form activity-form">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Activity.RecordId)
<div class="form-group">
#Html.LabelFor(model => model.Activity.Acres, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Activity.Acres, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Activity.Acres, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.Activity.Volume, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Activity.Volume, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Activity.Volume, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.Activity.Feet, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Activity.Feet, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Activity.Feet, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.Activity.Hours, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Activity.Hours, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Activity.Hours, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.Activity.Comment, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Activity.Comment, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Activity.Comment, "", new { #class = "text-danger" })
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" onclick="$.validator.unobtrusive.parse($('#editActivityForm'));" />
</div>
</div>
}
Model with attirbute added:
[AtLeastOneRequired("Acres,Volume,Feet,Hours", ErrorMessage = "Activity requires at least one measure - Acres, Volume, Feet or Hours.")]
public Nullable<int> Acres { get; set; }
public Nullable<int> Volume { get; set; }
public Nullable<int> Feet { get; set; }
public Nullable<int> Hours { get; set; }
The problem was with the client code. I finally found the client code was not being hit. I eventually found it was because the validation add was inside (function() {}). I deleted that 'ready' piece and now it works every time.

uploading pictures in application and saving path in database for MVC

i m stuck with uploading 3pictures, please suggest how can i move ahead
if you want i can email or upload my full solution for you guys
below is few detail:
My Controller:
namespace TiresalesClaim.Controllers
{
public class TsiclaimsController : Controller
{
private TiresalesClaimContext db = new TiresalesClaimContext();
// GET: Tsiclaims
public ActionResult Index(string searchBy, string search, int? page)
{
// var claims = db.Tsiclaims.Include(d => d.disposition).ToList();
if (searchBy == "DistributorName")
{
return View(db.Tsiclaims.Where(x => x.DistributorName.Contains(search) || search == null)
.ToList().ToPagedList(page ?? 1, 20));
}
else
if (searchBy == "TyreSize")
{
return View(db.Tsiclaims.Where(x => x.TyreSize.Contains(search) || search == null)
.ToList().ToPagedList(page ?? 1, 20));
}
else
if (searchBy == "TyreBrand")
{
return View(db.Tsiclaims.Where(x => x.TyreBrand.Contains(search) || search == null)
.ToList().ToPagedList(page ?? 1, 20));
}
else
if (searchBy == "Disposition")
{
return View(db.Tsiclaims.Where(x => x.DispositionAsPerTSI.Contains(search) || search == null)
.ToList().ToPagedList(page ?? 1, 20));
}
else
{
return View(db.Tsiclaims.ToList().ToPagedList(page ?? 1, 20));
}
}
public ActionResult OrderByDistributorName(int? page)
{
var claim = from c in db.Tsiclaims
orderby c.DistributorName ascending
select c;
return View((claim).ToPagedList(page ?? 1, 20));
}
public ActionResult OrderBySize(int? page)
{
var claim = from c in db.Tsiclaims
orderby c.TyreSize ascending
select c;
return View((claim).ToPagedList(page ?? 1, 20));
}
public ActionResult OrderByBrand(int? page)
{
var claim = from c in db.Tsiclaims
orderby c.TyreBrand ascending
select c;
return View((claim).ToPagedList(page ?? 1, 20));
}
public ActionResult OrderByDisposition(int? page)
{
var claim = from c in db.Tsiclaims
orderby c.DispositionAsPerTSI descending
select c;
return View((claim).ToPagedList(page ?? 1, 20));
}
public ActionResult OrderByDate(int? page)
{
var claim = from c in db.Tsiclaims
orderby c.ClaimRecDate descending
select c;
return View((claim).ToPagedList(page ?? 1, 20));
}
// GET: Tsiclaims/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Tsiclaim tsiclaim = db.Tsiclaims.Find(id);
if (tsiclaim == null)
{
return HttpNotFound();
}
return View(tsiclaim);
}
// GET: Tsiclaims/Create
public ActionResult Create()
{
TableDbContext tdb = new TableDbContext();
ViewBag.distributor = new SelectList(tdb.DistributorNames, "Name", "Name");
ViewBag.size = new SelectList(tdb.TyreSizes, "Name", "Name");
ViewBag.brand = new SelectList(tdb.TyreBrands, "Name", "Name");
ViewBag.Dispo = new SelectList(tdb.DispositionAsPerTSIs, "Name", "Name");
return View();
}
// POST: Tsiclaims/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,DistributorName,ClaimRecDate,State,Country,TelNo,FaxNo,Email,TyreSize,TyreBrand,TyreSerialNo,RemainingTreadDept,TreadWear,DefectAsPerDistributor,TypeofTyreWear,DefectAsPerTSI,DispositionAsPerTSI,ClaimValueAwarded,InspectedBy,Picture1,Picture2,Picture3")] Tsiclaim tsiclaim)
{
if (ModelState.IsValid)
{
db.Tsiclaims.Add(tsiclaim);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(tsiclaim);
}
// GET: Tsiclaims/Edit/5
public ActionResult Edit(int? id)
{
TableDbContext tdb = new TableDbContext();
ViewBag.distributor = new SelectList(tdb.DistributorNames, "Name", "Name");
ViewBag.size = new SelectList(tdb.TyreSizes, "Name", "Name");
ViewBag.brand = new SelectList(tdb.TyreBrands, "Name", "Name");
ViewBag.Dispo = new SelectList(tdb.DispositionAsPerTSIs, "Name", "Name");
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Tsiclaim tsiclaim = db.Tsiclaims.Find(id);
if (tsiclaim == null)
{
return HttpNotFound();
}
return View(tsiclaim);
}
// POST: Tsiclaims/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,DistributorName,ClaimRecDate,State,Country,TelNo,FaxNo,Email,TyreSize,TyreBrand,TyreSerialNo,RemainingTreadDept,TreadWear,DefectAsPerDistributor,TypeofTyreWear,DefectAsPerTSI,DispositionAsPerTSI,ClaimValueAwarded,InspectedBy,Picture1,Picture2,Picture3")] Tsiclaim tsiclaim)
{
if (ModelState.IsValid)
{
db.Entry(tsiclaim).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(tsiclaim);
}
// GET: Tsiclaims/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Tsiclaim tsiclaim = db.Tsiclaims.Find(id);
if (tsiclaim == null)
{
return HttpNotFound();
}
return View(tsiclaim);
}
// POST: Tsiclaims/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Tsiclaim tsiclaim = db.Tsiclaims.Find(id);
db.Tsiclaims.Remove(tsiclaim);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
My Create Page:
#model TiresalesClaim.Models.Tsiclaim
#
{
ViewBag.Title = "Create";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#*<h1>Tire Sales International</h1>*#
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#*<div class="form-group">
#Html.LabelFor(model => model.Id, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DisplayFor(model => model.Id, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Id, "", new { #class = "text-danger" })
</div>
</div>*#
<div class="form-group">
#Html.LabelFor(model => model.DistributorName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.DistributorName, (SelectList)ViewBag.distributor, "Select Distributor")
#*#Html.DropDownList("DistributorName", new List<SelectListItem> {
new SelectListItem{Text="Al Alaly Tyre", Value="Al Alaly Tyre"},
new SelectListItem{Text="Jilphar", Value="Jilphar"}
}, "Select Distributor Name")*#
#*#Html.EditorFor(model => model.DistributorName, new { htmlAttributes = new { #class = "form-control" } })*#
#Html.ValidationMessageFor(model => model.DistributorName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ClaimRecDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ClaimRecDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ClaimRecDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.State, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.State, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.State, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Country, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Country, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Country, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TelNo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TelNo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TelNo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FaxNo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FaxNo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FaxNo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TyreSize, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.TyreSize, (SelectList)ViewBag.size, "Select Tyre Size")
#*#Html.DropDownList("TyreSize", new List<SelectListItem> {
new SelectListItem{Text="GD 1200r24 20pr HF702", Value="GD 1200r24 20pr HF702"},
new SelectListItem{Text="GD 1200r24 20pr GD122", Value="GD 1200r24 20pr GD122"},
new SelectListItem{Text="TF 1200r24 20pr TF801", Value="TF 1200r24 20pr TF801"},
new SelectListItem{Text="TF 1200r24 20pr TF580", Value="TF 1200r24 20pr TF580"},
new SelectListItem{Text="YG 1200r24 20pr FH326", Value="YG 1200r24 20pr FH326"},
new SelectListItem{Text="GD 315/80r22.5 18pr GD660", Value="GD 315/80r22.5 18pr GD660"},
new SelectListItem{Text="GD 315/80r22.5 18pr GD768", Value="GD 315/80r22.5 18pr GD768"},
new SelectListItem{Text="YG 315/80r22.5 18pr FH158", Value="YG 315/80r22.5 18pr FH158"},
new SelectListItem{Text="YG 315/80r22.5 18pr FH159", Value="YG 315/80r22.5 18pr FH159"},
new SelectListItem{Text="GD 385/65r22.5 20pr GD022", Value="GD 385/65r22.5 20pr GD022"},
new SelectListItem{Text="YG 385/65r22.5 20pr FH538", Value="YG 385/65r22.5 20pr FH538"},
}, "Select Tyre Size")*#
#*#Html.EditorFor(model => model.TyreSize, new { htmlAttributes = new { #class = "form-control" } })*#
#Html.ValidationMessageFor(model => model.TyreSize, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TyreBrand, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.TyreBrand, (SelectList)ViewBag.brand, "Select Tyre Brand")
#*#Html.DropDownList("TyreBrand", new List<SelectListItem> {
new SelectListItem{Text="GreenDragon Brand Tyre", Value="GreenDragon Brand Tyre"},
new SelectListItem{Text="Tuffstone Brand Tyre", Value="Tuffstone Brand Tyre"},
new SelectListItem{Text="Young Brand Tyre", Value="Young Brand Tyre"}
}, "Select Tyre Brand")*#
#*#Html.EditorFor(model => model.TyreBrand, new { htmlAttributes = new { #class = "form-control" } })*#
#Html.ValidationMessageFor(model => model.TyreBrand, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TyreSerialNo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TyreSerialNo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TyreSerialNo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.RemainingTreadDept, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.RemainingTreadDept, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.RemainingTreadDept, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TreadWear, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TreadWear, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TreadWear, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DefectAsPerDistributor, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DefectAsPerDistributor, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DefectAsPerDistributor, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TypeofTyreWear, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TypeofTyreWear, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TypeofTyreWear, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DefectAsPerTSI, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DefectAsPerTSI, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DefectAsPerTSI, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DispositionAsPerTSI, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model=>model.DispositionAsPerTSI,(SelectList)ViewBag.Dispo, "Select Disposition")
#*#Html.DropDownList("DispositionAsPerTSI", new List<SelectListItem> {
new SelectListItem{Text="Pass", Value="Pass"},
new SelectListItem{Text="Fail", Value="Fail"}
}, "Select Disposition As Per TSI")*#
#*#Html.EditorFor(model => model.DispositionAsPerTSI, new { htmlAttributes = new { #class = "form-control" } })*#
#Html.ValidationMessageFor(model => model.DispositionAsPerTSI, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ClaimValueAwarded, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ClaimValueAwarded, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ClaimValueAwarded, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.InspectedBy, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.InspectedBy, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.InspectedBy, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Picture1, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Picture1, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Picture1, "", new { #class = "text-danger" })
<input type="file" class="form-control" id="Picture1"/>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Picture2, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Picture2, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Picture2, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Picture3, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Picture3, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Picture3, "", 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" />*#
<input type="image" src="~/Icons/Save.png" alt="Submit" width="40" height="40">
</div>
</div>
</div>}<div><img src="#Url.Content("~/Icons/go-back-icon.png")" width="50" />Back</div>#section Scripts {#Scripts.Render("~/bundles/jqueryval")}
My Model:
namespace TiresalesClaim.Models
{
public class Tsiclaim
{
[Key]
[DisplayName("Claim Ref#")]
public int Id { get; set; }
//[Key]
//[Range(1,999999)]
//public int Id { get; set; }
[Required]
[DisplayName("Distributor Name")]
public string DistributorName { get; set; }
[DataType(DataType.Date)]
[DisplayName("Claim Rec Date")]
public DateTime ClaimRecDate { get; set; }
[Required]
[DisplayName("State")]
public string State { get; set; }
[Required]
[DisplayName("Country")]
public string Country { get; set; }
[DataType(DataType.PhoneNumber)]
[DisplayName("Tel #")]
public string TelNo { get; set; }
[DisplayName("Fax #")]
[DataType(DataType.PhoneNumber)]
public string FaxNo { get; set; }
[DisplayName("Email")]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[Required]
[DisplayName("Tyre Size")]
public string TyreSize { get; set; }
[Required]
[DisplayName("Tyre Brand")]
public string TyreBrand { get; set; }
//[Required]
//public string PlyRating { get; set; }
[Required]
[DisplayName("Tyre Serial #")]
public string TyreSerialNo { get; set; }
[Required]
[DisplayName("Rmaining Tread Dept")]
public decimal RemainingTreadDept { get; set; }
[Required]
[DisplayName("% Tread Wear")]
public decimal TreadWear { get; set; }
[Required]
[DisplayName("Defect As Per Distributor")]
public string DefectAsPerDistributor { get; set; }
[Required]
[DisplayName("Type of Tyre Wear")]
public string TypeofTyreWear { get; set; }
[Required]
[DisplayName("Defect As Per TSI")]
public string DefectAsPerTSI { get; set; }
[Required]
[DisplayName("Disposition As Per TSI")]
public string DispositionAsPerTSI { get; set; }
[Required]
[DisplayName("% Claim Value Awarded")]
public decimal ClaimValueAwarded { get; set; }
[Required]
[DisplayName("Inspected By")]
public string InspectedBy { get; set; }
[DataType(DataType.Upload)]
public string Picture1 { get; set; }
[DataType(DataType.Upload)]
public string Picture2 { get; set; }
[DataType(DataType.Upload)]
public string Picture3 { get; set; }
[DisplayName("Status")]
public string Status { get; set; }
[DisplayName("Remarks")]
public string Remarks { get; set; }
//[NotMapped]
//public virtual DispositionAsPerTSI disposition { get; set; }
}
}
You need to get the file data from object containing the file data, i.e. HttpPostedFileBase. You can then get the data and the fully qualified name/path and save them separately as needed.
See this link for an example: Uploading a File (Or Files) With ASP.NET MVC
Here is a quick example:
VIEW:
<form action="" method="post" enctype="multipart/form-data">
<label for="file1">Filename:</label>
<input type="file" name="files" id="file1" />
<label for="file2">Filename:</label>
<input type="file" name="files" id="file2" />
<input type="submit" />
</form>
CONTROLLER:
[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files)
{
foreach (var file in files)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
}
return RedirectToAction("Index");
}

Resources