I have this model with required properties. Yes they are required for creating an item, but when I want to update a single column of them, I get this error about required fields. So it seems that my controller wants to update all of them.
In this case there's an item for sale and one can make an offer for it.
Part of my model:
public class Ad
{
public int AdID { get; set; }
[Required()]
[Display(Name = "Otsikko")]
public string Title { get; set; }
[Required()]
[DataType(DataType.MultilineText)]
[AllowHtml]
[Display(Name = "Kuvaus")]
public string Text { get; set; }
[Required()]
[DataType(DataType.Currency)]
[Display(Name = "Hinta")]
public float Price { get; set; }
[DataType(DataType.Currency)]
[Display(Name = "Tarjottu")]
public float Offer { get; set; }
My controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Offer([Bind(Include = "Offer")] Ad ad)
{
if (ModelState.IsValid)
{
db.Entry(ad).State = EntityState.Modified;
db.SaveChanges();
return RedirectToRoute("ilmoitus", new { id = ad.AdID });
}
else
{
var message = string.Join(" | ", ModelState.Values
.SelectMany(v => v.Errors)
.Select(e => e.ErrorMessage));
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, message);
}
}
Part of view:
#using (Html.BeginForm("Offer", "Ads"))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.AdID)
#Html.EditorFor(model => model.Offer, new { htmlAttributes = new { #class = "form-control offer-input", #placeholder = "Tarjoa..." } })
<button class="btn-default btn offer-btn">Tarjoa {{offer}} €</button>
}
I've tried this with same error How to Update only single field using EF
I got it working like this, included all the other properties as hidden and bound them in the controller:
View:
#using (Html.BeginForm("Offer", "Ads"))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.AdID)
#Html.HiddenFor(model => model.Title)
#Html.HiddenFor(model => model.Text)
#Html.HiddenFor(model => model.Price)
#Html.HiddenFor(model => model.Location)
#Html.HiddenFor(model => model.PaymentOptions)
#Html.HiddenFor(model => model.DeliveryOptions)
#Html.HiddenFor(model => model.SellerEmail)
#Html.EditorFor(model => model.Offer, new { htmlAttributes = new { #class = "form-control offer-input", #placeholder = "Tarjoa..." } })
<button class="btn-default btn offer-btn">Tarjoa {{offer}} €</button>
}
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Offer([Bind(Include = "AdID,Title,Text,Price,Offer,Location,PaymentOptions,DeliveryOptions,SellerEmail")] Ad ad)
{
if (ModelState.IsValid)
{
db.Entry(ad).State = EntityState.Modified;
db.SaveChanges();
return RedirectToRoute("ilmoitus", new { id = ad.AdID });
}
else
{
var message = string.Join(" | ", ModelState.Values
.SelectMany(v => v.Errors)
.Select(e => e.ErrorMessage));
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, message);
}
}
Is this a security issue though?
I have two solution for the above query.
You can use two different models for updating and insertion example
Remove the properties from ModelState then TryUpdateModel
public ActionResult UpdateAd(Ad ad)
{
ModelState.Remove("Title");
ModelState.Remove("Text");
ModelState.Remove("Price");
var p = GetAd();
if (TryUpdateModel(p))
{
//Save Changes;
}
}
Related
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 4 years ago.
This model is used to define a view:
namespace OnlineStore.ViewModels
{
public class SubCategoryVM
{
[Key]
public int ID { get; set; }
[Required]
public virtual string Name { get; set; }
[Required(ErrorMessage = "Parent Category Name is required")]
public virtual string ParentName { get; set; }
public IEnumerable<SelectListItem> categoryNames { get; set; }
}
}
Inside controller:
public ActionResult createSubCategory()
{
SubCategoryVM model = new SubCategoryVM();
var cNames = db.Categories.ToList();
model.categoryNames = cNames.Select(x
=> new SelectListItem
{
Value = x.Name,
Text = x.Name
});
return View(model);
}
[HttpPost]
public ActionResult createSubCategory(int? id, SubCategoryVM model)
{
SubCategory sc = new SubCategory();
if (ModelState.IsValid)
{
sc.ParentName = model.ParentName;
sc.Name = model.Name;
}
return View();
}
and View:
#model OnlineStore.ViewModels.SubCategoryVM
<div class="form-group">
#Html.LabelFor(model => model.ParentName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.ParentName, Model.categoryNames, "--Please select an option--", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ParentName, "", new { #class = "text-danger" })
</div>
This code is throwing a null-reference exception on line #Html.DropDownListFor(model => model.ParentName, Model.categoryNames, "--Please select an option--", new { #class = "form-control" }) saying:
Model.categoryName (Object reference not set to an instance of an object).
Please help me debug it.
Thanks in advance.
Problem is when you are posting the form and returning the View with the form data in case of invalid form, categoryNames in the model is becoming null and you have to repopulate the categoryNames before returning the view with model again.
So update your createSubCategory post method as follows:
[HttpPost]
public ActionResult createSubCategory(int? id, SubCategoryVM model)
{
SubCategory sc = new SubCategory();
if (ModelState.IsValid)
{
sc.ParentName = model.ParentName;
sc.Name = model.Name;
}
var cNames = db.Categories.ToList();
model.categoryNames = cNames.Select(x
=> new SelectListItem
{
Value = x.Name,
Text = x.Name
});
return View(model);
}
I have a people controller for user management and I'm trying to figure out how to get the dropdown choice when the user submits from the edit page. Whenever I hit submit on the page, none of the values from the view model seem to carry through to the post. I can't get the value they chose from the drop down to set the role.
See view model below:
public class PersonViewModel
{
public int PersonId { get; set; }
[Display(Name = "Full Name")]
public string FullName { get; set; }
public string Email { get; set; }
[Display(Name = "Current Role")]
public string SetRole { get; set; }
public List<RoleListViewModel> Roles { get; set; }
}
See controller edit functions below:
// GET: People/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Person person = db.people.Find(id);
if (person == null)
{
return HttpNotFound();
}
PersonViewModel pvm = new PersonViewModel();
List<IdentityRole> roles = adb.Roles.ToList();
var rlvm = new List<RoleListViewModel>();
roles.ForEach(x => rlvm.Add(new RoleListViewModel { RoleId = x.Id, RoleName = x.Name }));
pvm.PersonId = person.PersonId;
pvm.FullName = person.FirstName + " " + person.LastName;
pvm.Email = person.Email;
pvm.Roles = rlvm;
ViewBag.RoleList = new SelectList(rlvm, "RoleName", "RoleName", person.CurrentRole);
return View(pvm);
}
// POST: People/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(PersonViewModel pvm)
{
if (ModelState.IsValid)
{
db.Entry(pvm).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
var usr = new AccountController();
var pers = db.people.Where(x => x.PersonId == pvm.PersonId).FirstOrDefault();
usr.UserManager.AddToRoleAsync(pers.NetId, /* their choice should go here but how? */);
db.SaveChanges();
return View(pvm);
}
Here is the cshtml:
<div class="form-group">
#Html.LabelFor(model => model.Roles, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="form-control-static">
#Html.DropDownList("RoleList", null, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Roles, "", new { #class = "text-danger" })
</div>
</div>
Make a variable in your View Model to store the selected value and then in the view use
#Html.DropDownListFor(m => m.SelectedRoleVariable, RolesSelectList, new { #class = "form-control" });
What I'm trying to do...
I am trying to get a newly added item to display in a cascading dropdownlist.
Overview...
The first dropdownlist (I'll call it ddlCategory) is for selecting a Category of electrical devices (ie. Appliances, Audio-Visual, Lighting, etc.). The second dropdownlist (I'll call ddlElecDev) is populated with the devices which are filtered by the selected Category. If the device isn't listed in ddlElecDev then the user can click a link to add a new one. After saving the newly added electrical device, the user is redirected back to the original page with the electrical device id as a parameter.
All the above seems to work fine. However, when the user is redirected to the first page, not only is the newly added electrical device not selected in ddlElecDev, but it doesn't even appear in the list. Strangely, if I refresh the page, it is automatically selected.
Can anyone explain to me how to get the newly added device to be selected without having to refresh the page?
Here's the markup for selecting the category and electrical device:
<div class="form-group">
#Html.LabelFor(model => model.SelectedCategory, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.SelectedCategory, Model.Categories, "Select a Category", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.SelectedCategory, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ElectricalDeviceID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.CascadingDropDownListFor(
expression: model => model.ElectricalDeviceID,
triggeredByProperty: model => model.SelectedCategory,
url: Url.Action("GetElectricalDevices", "ElectricalDeviceConfigurations"),
ajaxActionParamName: "categoryId",
optionLabel: "Select an Electrical Device",
disabledWhenParrentNotSelected: false,
htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ElectricalDeviceID, "", new { #class = "text-danger" })
#Html.ActionLink("Not Listed? Add a new Electrical Device", "AddNew", "ElectricalDevices", new { returnUrl = string.Format("/ElectricalDeviceConfigurations/AddConfiguration?eventVendorId={0}", Model.EventVendorID) }, null)
</div>
</div>
The documentation for the Cascading DropDownList Helper can be found at
https://github.com/alexanderar/Mvc.CascadeDropDown
Here's the Controller method for selecting the Electrical Device:
public ActionResult AddConfiguration(int? eventVendorId, int? newElecDev)
{
(Some code removed for brevity)
var selectedCategoryId = db.ElectricalDeviceCategoryLookups.Where(cat => cat.Category == Enums.ElectricalDeviceCategory.All).FirstOrDefault().ID;
var electricalDeviceID = (newElecDev.HasValue) ? newElecDev : null;
return View(new ElecDevConfigSelectionViewModel { EventVendorID = eventVendorId, EventVendor = eventVendor, Categories = GetCategories(), SelectedCategory = selectedCategoryId, ElectricalDeviceID = electricalDeviceID });
}
Here's the controller methods for populating the Categories and the Electrical Devices:
private List<SelectListItem> GetCategories()
{
var categories = new List<SelectListItem>();
db.ElectricalDeviceCategoryLookups.OrderBy(c => c.Description).ToList().ForEach(item => categories.Add(new SelectListItem { Text = item.Description, Value = item.ID.ToString() } ));
return categories;
}
public ActionResult GetElectricalDevices(int? categoryId)
{
if (categoryId.HasValue)
{
var selCategory = db.ElectricalDeviceCategoryLookups.Where(cat => cat.ID == categoryId).FirstOrDefault().Category;
var elecDevicesSelectList = new List<SelectListItem>();
var elecDevices = (selCategory == Enums.ElectricalDeviceCategory.All) ? db.ElectricalDevices.OrderBy(ed => ed.Name).ToList() : db.ElectricalDevices.Where(ed => ed.Category == selCategory).OrderBy(ed => ed.Name).ToList();
elecDevices.ForEach(ed => elecDevicesSelectList.Add(new SelectListItem { Text = ed.Name, Value = ed.ID.ToString() }));
return Json(elecDevicesSelectList, JsonRequestBehavior.AllowGet);
}
return null;
}
Here's the View Model:
public class ElecDevConfigSelectionViewModel
{
public int? EventVendorID { get; set; }
public EventVendor EventVendor { get; set; }
[Display(Name = "Category")]
public int SelectedCategory { get; set; }
public IList<SelectListItem> Categories { get; set; }
[Display(Name = "Electrical Device")]
public int? ElectricalDeviceID { get; set; }
}
Here's the controller methods for adding a new electrical device:
// GET: ElectricalDevices/AddNew
public ActionResult AddNew(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
var selectedCategoryId = db.ElectricalDeviceCategoryLookups.FirstOrDefault().ID;
return View(new AddNewElectricalDeviceViewModel { ReturnUrl = returnUrl, Categories = GetCategories(), SelectedCategory = null });
}
// POST: ElectricalDevices/AddNew
// 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 AddNew(AddNewElectricalDeviceViewModel model)
{
if (ModelState.IsValid)
{
var selectedCategory = db.ElectricalDeviceCategoryLookups.Find(model.SelectedCategory);
var electricalDevice = new ElectricalDevice
{
Name = model.ElectricalDevice.Name,
Description = model.ElectricalDevice.Description,
Category = selectedCategory.Category,
Wattage = model.ElectricalDevice.Wattage
};
db.ElectricalDevices.Add(electricalDevice);
db.SaveChanges();
var returnUrl = string.Format("{0}&newElecDev={1}", model.ReturnUrl, electricalDevice.ID);
return RedirectToLocal(returnUrl);
}
return View();
}
Here's the View Model for adding a new electrical device:
public class AddNewElectricalDeviceViewModel
{
public string ReturnUrl { get; set; }
[Display(Name = "Category")]
public int? SelectedCategory { get; set; }
public IList<SelectListItem> Categories { get; set; }
public ElectricalDevice ElectricalDevice { get; set; }
}
I wonder why i get null model passing from the view to the controller.
Here is my code in the view (UpdatePersonal.cshtml):
#model Project.Models.UserInfo
#using (Html.BeginForm()){
#Html.LabelFor(m => m.userinfo.firstname);
#Html.TextBoxFor(m => m.userinfo.firstname, new { #Value = ViewBag.Firstname });
#Html.LabelFor(m => m.userinfo.lastname);
#Html.TextBoxFor(m => m.userinfo.lastname, new { #Value = ViewBag.Lastname });
#Html.LabelFor(m => m.userinfo.email);
#Html.TextBoxFor(m => m.userinfo.email, new { #Value = ViewBag.Email });
#Html.LabelFor(m => m.userinfo.phone);
#Html.TextBoxFor(m => m.userinfo.phone, new { #Value = ViewBag.Phone });
#Html.HiddenFor(m => m.username, new { #Value = ViewBag.Username });
<input type="submit" value="Submit" />}
Here is the action method that accepts it:
[HttpPost]
[AllowAnonymous]
public ActionResult UpdatePersonal(UserInfo userInfo){
//some code here
//my breakpoint}
i see the model being passed has null value as i used breakpoint
my model:
public class UserInfo
{
[BsonId]
public string username { get; set; }
public Info userinfo { get; set; }
public Address address { get; set; }
public class Info
{
public string firstname { get; set; }
public string lastname { get; set; }
public string email { get; set; }
public string phone { get; set; }
}
public class Address
{
public string street { get; set; }
public string address1 { get; set; }
public string address2 { get; set; }
public string postalcode { get; set; }
public string country { get; set; }
}
}
You work around the problem but your first code was good, the only problem was the name of your action method param was the same that the name of your model property.
Change your action method signature for example by :
public ActionResult UpdatePersonal(UserInfo info)
and it should be work !
I just solved my problem, instead i used and pass the subclass
#model Buch_Ankauf.Models.UserInfo.Info
#using (Html.BeginForm()){
#Html.LabelFor(m => m.firstname);
#Html.TextBoxFor(m => m.firstname, new { #Value = ViewBag.Firstname });
#Html.LabelFor(m => m.lastname);
#Html.TextBoxFor(m => m.lastname, new { #Value = ViewBag.Lastname });
#Html.LabelFor(m => m.email);
#Html.TextBoxFor(m => m.email, new { #Value = ViewBag.Email });
#Html.LabelFor(m => m.phone);
#Html.TextBoxFor(m => m.phone, new { #Value = ViewBag.Phone });
#Html.Hidden("username", new { #Value = ViewBag.Username });
<input type="submit" value="Submit" />}
in my controller:
[HttpPost]
[AllowAnonymous]
public ActionResult UpdatePersonal(UserInfo.Info userInfo)
{
I have a pretty complex model and a view (below). I only have ONE of my fields as Required (Key Active Mg). When I mark this [Required(ErrorMessage="Key Active Mg is required")] and set the #Html.ValidationMessageFor for that field, my app will let me enter nothing and click Save. Of course, Model.IsValid will return false. It doesn't come back and outline the field in red indicating it's required. Does anyone know why?
My model:
public class RawValues
{
[Key]
public int Pk { get; set; }
public int? FillerFk { get; set; }
[Display(Name = "Filler")]
[ForeignKey("FillerFk")]
public virtual Filler Filler { get; set; }
public int? CapsuleFk { get; set; }
[Display(Name = "Capsule")]
[ForeignKey("CapsuleFk")]
public virtual Capsule Capsule { get; set; }
public int? KeyActiveFk { get; set; }
[Display(Name = "Key Active")]
[ForeignKey("KeyActiveFk")]
public virtual KeyActive KeyActive { get; set; }
[Display(Name="API #1")]
public int? Active1 { get; set; }
[Display(Name = "API #2")]
public int? Active2 { get; set; }
[Display(Name = "API #3")]
public int? Active3 { get; set; }
[Display(Name = "API #4")]
public int? Active4 { get; set; }
[Display(Name = "API #5")]
public int? Active5 { get; set; }
[Display(Name = "Key Active Mg")]
[Required(ErrorMessage="Key Active Mg is required.")]
public int KeyActiveMg { get; set; }
[Display(Name = "E4M")]
public bool E4M { get; set; }
[Display(Name = "K100M")]
public bool K100M { get; set; }
public int TimeReleaseFillerFk { get; set; }
public int NumberCapsules { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedDate { get; set; }
}
My View:
#model CapWorx.QuikCap.Models.RawValues
#* This partial view defines form fields that will appear when creating and editing entities *#
<div data-role="fieldcontain">
#Html.LabelFor(model => model.Capsule, new { #class = "ui-input-text" })
#Html.DropDownListFor(m => m.Capsule.Pk, new SelectList(ViewBag.Capsules, "Pk", "Name", "Pk"))
</div>
<div data-role="fieldcontain">
#Html.LabelFor(model => model.Active1)
#Html.EditorFor(model => model.Active1)
</div>
<div data-role="fieldcontain">
#Html.LabelFor(model => model.Active2)
#Html.EditorFor(model => model.Active2)
</div>
<div data-role="fieldcontain">
#Html.LabelFor(model => model.Active3)
#Html.EditorFor(model => model.Active3)
</div>
<div data-role="fieldcontain">
#Html.LabelFor(model => model.Active4)
#Html.EditorFor(model => model.Active4)
</div>
<div data-role="fieldcontain">
#Html.LabelFor(model => model.Active5)
#Html.EditorFor(model => model.Active5)
</div>
<div data-role="fieldcontain">
#Html.LabelFor(model => model.KeyActive, new { #class = "ui-input-text" })
#Html.DropDownListFor(m => m.KeyActive.Pk, new SelectList(ViewBag.KeyActives, "Pk", "Name", "Pk"))
</div>
<div data-role="fieldcontain">
#Html.LabelFor(model => model.KeyActiveMg)
#Html.EditorFor(model => model.KeyActiveMg)
#Html.ValidationMessageFor(model => model.KeyActiveMg)
</div>
<div data-role="fieldcontain">
#Html.LabelFor(model => model.E4M)
#Html.DropDownListFor(x => x.E4M,
new[] {
new SelectListItem() { Text = "Off", Value = "False", Selected = true },
new SelectListItem() { Text = "On", Value = "True" } },
new { data_role = "slider" })
</div>
<div data-role="fieldcontain">
#Html.LabelFor(model => model.K100M)
#Html.DropDownListFor(x => x.K100M,
new[] {
new SelectListItem() { Text = "Off", Value = "False", Selected = true },
new SelectListItem() { Text = "On", Value = "True" } },
new { data_role = "slider" })
</div>
<div data-role="fieldcontain">
#Html.LabelFor(model => model.Filler, new { #class = "ui-input-text" })
#Html.DropDownListFor(m => m.Filler.Pk, new SelectList(ViewBag.Fillers, "Pk", "Name", "Pk"))
#Html.ValidationMessage("FillerName", "Filler is required")
</div>
My Controller:
[HttpPost]
public ActionResult Create(RawValues rawvalues)
{
rawvalues.CreatedBy = User.Identity.Name;
rawvalues.CreatedDate = DateTime.Now;
rawvalues.TimeReleaseFillerFk = Helpers.OperationContext.GetTimeReleaseFillerFk(rawvalues.E4M, rawvalues.K100M);
rawvalues.CapsuleFk = rawvalues.Capsule.Pk;
rawvalues.FillerFk = rawvalues.Filler.Pk;
rawvalues.KeyActiveFk = rawvalues.KeyActive.Pk;
rawvalues.Filler = Helpers.OperationContext.GetFiller(rawvalues.Filler.Pk);
rawvalues.Capsule = Helpers.OperationContext.GetCapsule(rawvalues.Capsule.Pk);
rawvalues.KeyActive = Helpers.OperationContext.GetKeyActive(rawvalues.KeyActive.Pk);
rawvalues.NumberCapsules = 100;
var errors = ModelState.Values.SelectMany(v => v.Errors);
if (ModelState.IsValid) {
rawvaluesRepository.InsertOrUpdate(rawvalues);
rawvaluesRepository.Save();
List<Results> results = Helpers.OperationContext.CallCalculate(rawvalues);
return View("Results", results);
} else {
ViewBag.Error = "Model State was not valid.";
return View("Error");
}
}
My screenshot:
UPDATE
I've updated my controller code to be the following:
if (ModelState.IsValid) {
rawvaluesRepository.InsertOrUpdate(rawvalues);
rawvaluesRepository.Save();
List<Results> results = Helpers.OperationContext.CallCalculate(rawvalues);
return View("Results", results);
} else {
ViewBag.Capsules = Helpers.OperationContext.GetCapsules();
ViewBag.Fillers = Helpers.OperationContext.GetFillers();
ViewBag.KeyActives = Helpers.OperationContext.GetKeyActives();
return View();
}
This resolves my issue. I needed to return the same View to display the errors on the screen. With DataAnnotations Validation, the form does in fact hit the HttpPost method of Create, and if there are errors (validation errors) the ModelState.IsValid will return false, in which case I need to return the same view. See screenshot below!
Looks like you are returning another view (Error) if ModelState.IsValid is false. You should return the posted viewmodel to the same create view.
public ActionResult Create(RawValues model)
{
if(ModelState.IsValid)
{
//everything is good. Lets save and redirect
}
return View(model);
}
My guess is that you are not including 'jquery.unobtrusive-ajax.min.js' and/or 'jquery.validate.unobtrusive.min.js'. I believe these are required to interpret the metadata added by DataAnnotations and supply the validation methods your looking for.
When your model is invalid, you don't actually return it with it's validation errors. Then, you do this:
#Html.ValidationMessageFor(model => model.KeyActiveMg)
but there is no Validation Message for anything. You returned a brand new view with a blank Model. Instead, you should return your invalid model to the view, like such:
return View(rawvalues);
UPDATE
Your controller should look like this:
public ActionResult Create()
{
return View(new RawValues());
}
[HttpPost]
public ActionResult Create(RawValues model)
{
if (ModelState.IsValid)
{
// Do stuff
}
else
{
return View(model);
}
}
Your view seems fine, so it should work from here.
If you're talking about client side validation, you need to reference the necessary JS files. They should be already preconfigured in your Bundle config. You just need to add to your view:
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/jqueryval")
Just to make sure, your BundleConfig class that sits in the App_Start folder should have these:
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
"~/Scripts/jquery-ui-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
I think you need this
[HttpPost]
public ActionResultCreate(RawValues model)
{
....
if (!ModelState.IsValid)
{
ModelState.AddModelError("KeyActiveMg", "KeyActiveMg field is required");
var model = new GetModel();
return View("Results", model);
}
rawvaluesRepository.InsertOrUpdate(rawvalues);
rawvaluesRepository.Save();
List<Results> results = Helpers.OperationContext.CallCalculate(rawvalues);
return View("Results", results);
}