C# MVC form doesn't work with input form attribute - asp.net-mvc

I need to use form inside table cell with fields in another cells. I'm using input form attribute. MVC passing data to controller works correctly but validation before form send doesn't work with this attribute.
<tr>
<td>
#Html.EditorFor(model => item.Code, new { htmlAttributes = new { #class = "form-control inline-edit", form = "editForm" + item.Id } })
#Html.ValidationMessageFor(model => item.Code)
</td>
<td>
#Html.EditorFor(model => item.Name, new { htmlAttributes = new { #class = "form-control inline-edit", form = "editForm" + item.Id } })
#Html.ValidationMessageFor(model => item.Name)
</td>
<td class="text-right">
#using (Html.BeginForm("UpdatePrintMaterial", "Production", FormMethod.Post, new { id = "editForm" + item.Id }))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => item.Id)
<button class="btn btn-default save" data-toggle="tooltip" title="Zapisz"><i class="fa fa-save"></i></button>
}
</td></tr>
How to workaroud this issue to use validation before sending data?

Related

Calling a Partialview with table on the main view

I'm trying to call a partial view with details table for some items. However, the partial view does not show any record in the main view. How I can call the Patrial view successfully? the partial view as follows:
#model IDECOHealthInsurance.Models.Pharmacy
#using (Html.BeginForm("pharmacyDetials", "Pharmacy"))
{
<h4>تفاصيل الصيدلية</h4>
<div id="dvPatientNotice" class="MainGridContainer pb-5">
#if (Model.dtItemsDetails != null)
{
<table dir="rtl" id="Paitents" class="MainGrid">
<thead>
<tr style="text-size-adjust:auto">
<th>
رقم الموظف
</th>
<th>
التاريخ
</th>
<th>
الوقت
</th>
<th>
المستفيدون
</th>
<th>
ملاحظات
</th>
<th>
الباركورد
</th>
<th>
أسم العينة
</th>
<th>
الكمية
</th>
<th>
السعر
</th>
</tr>
</thead>
<tbody>
#foreach (System.Data.DataRow row in Model.dtItemsDetails.Rows)
{
<tr style="width:100%">
<td>
#row["EMPLOYEE_NUMBER"]
</td>
<td>
#row["ENTRY_DATE"]
</td>
<td>
#row["ENTRY_TIME"]
</td>
<td>
#row["BENEFICIARIES"]
</td>
<td>
#row["NOTE"]
</td>
<td>
#row["ITEM_CODE"]
</td>
<td>
#row["ITEM_NAME"]
</td>
<td>
#row["QTY"]
</td>
<td>
#row["PRICE"]
</td>
</tr>
}
</tbody>
</table>
}
</div>
}
The controller as follows:
[HttpGet]
public ActionResult pharmacyDetials(Pharmacy model)
{
var masterID = Convert.ToInt32(Session["login"]);
if (masterID == 0)
{
return RedirectToAction("Login");
}
else
{
Models.Pharmacy objPharamcyMode = new Pharmacy();
IDECOServiceReference.IdecoAPIServiceClient idecoAPI = new IDECOServiceReference.IdecoAPIServiceClient();
DataTable dataTable = idecoAPI.GETPHARMACYEMPLOYEEMASTER("", 1);
model.dtItemsDetails = dataTable;
return PartialView("_PharmacyDetails", model);
}
}
And the Main view as follows:
#model IDECOHealthInsurance.Models.Pharmacy
#{
ViewBag.Title = "PharmacyApplication";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<table style="height:680px; width:1280px; border:hidden">
<tr>
<td>
<div id="pDetail">
#Html.Partial("_PharmacyDetails", Model)
</div>
</td>
<td>
#using (Ajax.BeginForm("PharmacyApplication", "Pharmacy", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "updatePnl", InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace, LoadingElementId = "Loading", OnBegin = "" }))
{
<div class="form-horizontal">
<div class="form-group">
#Html.LabelFor(model => model.PHARMACY_NAME, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DisplayFor(model => model.PHARMACY_NAME)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EMPLOYEE_NUMBER, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EMPLOYEE_NUMBER, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EMPLOYEE_NUMBER, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ENTRY_DATE, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DisplayFor(model => model.ENTRY_DATE, new { htmlAttributes = new { #class = "form-control", #Value = DateTime.Today.ToString("dd/MM/yyyy"), #readonly = "readonly" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ENTRY_TIME, new { htmlAttributes = new { #class = "form-control", #Value = DateTime.Today.ToString("HH:mm:ss"), #readonly = "readonly" } })
<div class="col-md-10">
#Html.DisplayFor(model => model.ENTRY_TIME)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BENEFICIARIES, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
زوجة #Html.RadioButtonFor(m => m.BENEFICIARIES, 1)
أبن #Html.RadioButtonFor(m => m.BENEFICIARIES, 2)
أبنة #Html.RadioButtonFor(m => m.BENEFICIARIES, 3)
الموظف #Html.RadioButtonFor(m => m.BENEFICIARIES, 4)
#Html.ValidationMessageFor(model => model.BENEFICIARIES, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Note, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<textarea name="NOTE" id="comments" style="font-family:'Times New Roman';font-size:1.2em; width: 280px; height:auto" placeholder="أكتب ملاحظاتك هنا"></textarea>
#Html.ValidationMessageFor(model => model.Note, "", new { #class = "text-danger" })
</div>
</div>
<div id="showPnl">
<input class="btn btn-default" type="button" value="تفاصيل الصيدلية" onclick="#("window.location.href='" + #Url.Action("pharmacyDetials", "Pharmacy") + "'");" />
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" id="panel" value="أضافة" class="btn btn-default" />
</div>
<input class="btn btn-default" type="button" value="خروج" onclick="#("window.location.href='" + #Url.Action("LogOut", "Pharmacy") + "'");" />
</div>
</div>
}
</td>
</tr>
</table>
<div id="updatePnl">
#Html.Partial("_PartialPharmacyDetails", Model)
</div>
<br />
<br />
<br />
<div id="pnlItemsDetails">
#Html.Partial("_PartialItemsDetails", Model)
</div>
When I click on the pharmacy details (in Arabic) = "تفصيل الصيدلية" button it redirects me to another page which contains the desired table that I want to show in the main view. However, I don't want this to happen I want to show the table without clicking on the button. Could you explain why this problem happened?
The Result at the run time appears as follows:
Result of the application at run time
If you want to prevent your page from redirecting, you've to use an ajax request. Replace below line :
<input class="btn btn-default" type="button" value="تفاصيل الصيدلية" onclick="#("window.location.href='" + #Url.Action("pharmacyDetials", "Pharmacy") + "'");" />
with :
<input class="btn btn-default" type="button" value="تفاصيل الصيدلية" onclick="getPharmacyDetails();" />
and in your javascript section, add below code :
function getPharmacyDetails()
{
$.ajax({
url : '#Url.Content("~/Pharmacy/pharmacyDetials")',
type: "GET",
success: function (result) {
$("#pDetail").html(result);
}
});
}
Also, replace below HTML :
<div id="pDetail">
#Html.Partial("_PharmacyDetails", Model)
</div>
With :
<div id="pDetail"></div>
The above ajax request will execute the partial view and fill the pDetial div with the required result. Try it and Let me know if you've any query.

Why will the scripts on this view not run

I am trying to create an expandable input table and I am running into some issues. Both seem to be related to the fact that the scripts are not running, but I am not sure. None of the buttons are working even though they have in the past. I don't know what changed, but I did not change the add or delete functions but they don't work anymore. The submit button doesn't seem to trigger the corresponding function in the controller.
I have tried looking for syntax errors and there don't seem to be any. The scripts seem to be referencing the correct portion of the view.
Here is the controller:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Promotion_Generator.Models.DataModels;
namespace Promotion_Generator.Controllers
{
public class PromotionController : Controller
{
private PromotionGeneratorEntities db = new PromotionGeneratorEntities();
public ActionResult BOGO()
{
return View();
}
[HttpPost]
public JsonResult BOGOSave(string BuyMemberData, string GetMemberData)
{
try
{
var BuySerializeData = JsonConvert.DeserializeObject<List<String>>(BuyMemberData);
foreach (var data in BuySerializeData)
{
}
var GetSerializeData = JsonConvert.DeserializeObject<List<String>>(GetMemberData);
foreach (var data in GetSerializeData)
{
}
db.SaveChanges();
}
catch (Exception)
{
return Json("fail");
}
return Json("success");
}
}
}
Here is the View
#model Promotion_Generator.Models.BOGOModel
#{
ViewBag.Title = "BOGO";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2><b>Buy One Get One Free</b></h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<p class = "control-label col-md-2"><b>Promotion Code</b></p>
<div class="col-md-10">
#Html.EditorFor(model => model.PROMOTION_CODE, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PROMOTION_CODE, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<p class="control-label col-md-2"><b>Description</b></p>
<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">
<p class="control-label col-md-2"><b>Start Date Time</b></p>
<div class="col-md-10">
#Html.EditorFor(model => model.START_DATE_TIME, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.START_DATE_TIME, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<p class="control-label col-md-2"><b>End Date Time</b></p>
<div class="col-md-10">
#Html.EditorFor(model => model.END_DATE_TIME, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.END_DATE_TIME, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<p class="control-label col-md-2"><b>Percent Off</b></p>
<div class="col-md-10">
#Html.EditorFor(model => model.PERCENT_OFF, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PERCENT_OFF, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<p class="control-label col-md-2"><b>Percent Off</b></p>
<div class="col-md-10">
#Html.EditorFor(model => model.BUY_MEMBERS, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PERCENT_OFF, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group col-md-10">
<h3><b>Buy Products</b></h3>
<table id="buyProducts" class="table">
<thread>
<tr>
<th>
<p>Product UPC</p>
</th>
</tr>
</thread>
<tbody>
<tr>
<td>
#Html.EditorFor(modelItem => modelItem.BUY_MEMBERS, new { htmlAttributes = new { #class = "form-control" } })
</td>
<td>
<input type="button" value="Remove" onclick="T1Remove(this)" />
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<input class="btn btn-default" id="btnAdd1" type="button" name="name" value="Add" />
</td>
</tr>
</tfoot>
</table>
</div>
<div class="form-group col-md-10">
<h3><b>Get Products</b></h3>
<table id="getProducts" class="table">
<thread>
<tr>
<th>
<p>Product UPC</p>
</th>
</tr>
</thread>
<tbody>
<tr>
<td>
#Html.EditorFor(modelItem => modelItem.GET_MEMBERS, new { htmlAttributes = new { #class = "form-control" } })
</td>
<td>
<input type="button" value="Remove" onclick="T2Remove(this)" />
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<input class="btn btn-default" id="btnAdd2" type="button" name="name" value="Add" />
</td>
</tr>
</tfoot>
</table>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" id="btnSubmit" value="Submit" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to Home", "Index", "Home")
</div>
#section scripts{
<script>
$(".btnAdd1").click(function () {
//Get the reference of the Table's TBODY element.
var tBody = $("#buyProducts > TBODY")[0];
//Add Row.
var row = tBody.insertRow(-1);
//Add Editor cell.
var cell = $(row.insertCell(-1));
cell.append("#Html.EditorFor(modelItem => modelItem.GET_MEMBERS, new { htmlAttributes = new { #class = "form-control" } })");
//Add Button cell.
cell = $(row.insertCell(-1));
var btnRemove = $("<input />");
btnRemove.attr("type", "button");
btnRemove.attr("onclick", "T1Remove(this);");
btnRemove.val("Remove");
cell.append(btnRemove);
//Clear the TextBoxes.
txtName.val("");
txtCountry.val("");
});
$(".btnAdd2").click(function () {
//Get the reference of the Table's TBODY element.
var tBody = $("#getProducts > TBODY")[0];
//Add Row.
var row = tBody.insertRow(-1);
//Add Editor cell.
var cell = $(row.insertCell(-1));
cell.append("#Html.EditorFor(modelItem => modelItem.GET_MEMBERS, new { htmlAttributes = new { #class = "form-control" } })");
//Add Button cell.
cell = $(row.insertCell(-1));
var btnRemove = $("<input />");
btnRemove.attr("type", "button");
btnRemove.attr("onclick", "T2Remove(this);");
btnRemove.val("Remove");
cell.append(btnRemove);
//Clear the TextBoxes.
txtName.val("");
txtCountry.val("");
});
function T1Remove(button) {
//Determine the reference of the Row using the Button.
var row = $(button).closest("TR");
var name = $("TD", row).eq(0).html();
if (confirm("Do you want to delete: " + name)) {
//Get the reference of the Table.
var table = $("#buyProducts")[0];
//Delete the Table row using it's Index.
table.deleteRow(row[0].rowIndex);
}
};
function T2Remove(button) {
//Determine the reference of the Row using the Button.
var row = $(button).closest("TR");
var name = $("TD", row).eq(0).html();
if (confirm("Do you want to delete: " + name)) {
//Get the reference of the Table.
var table = $("#getProducts")[0];
//Delete the Table row using it's Index.
table.deleteRow(row[0].rowIndex);
}
};
function BuyMembers() {
var BuyMembers = $(this).find('#BuyMembers').val();
return BuyMembers;
};
function GetMembers() {
var GetMembers = $(this).find('#GetMembers').val();
return GetMembers;
};
$('.btnSubmit').click(function () {
$.ajax({
url: '/Promotion/SaveData',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(BuyMembers),
data: JSON.stringify(GetMembers),
success: function () {
alert("Data Added Successfully");
},
error: function () {
alert("Error while inserting data");
}
});
});
</script>
}
When I hit the Add, Remove, and Submit buttons the script doesn't seem to run and no columns are added or deleted.
You're currently assigning the jQuery events to the classes ($(".btnAdd1")) instead of ids ($("#btnAdd1")). You can either change your events to link to the id values:
$("#btnAdd1").click(function () {
//...
}
$("#btnAdd2").click(function () {
//...
});
$('#btnSubmit').click(function () {
//...
});
or change the inputs to have the classes of the events. This will fix your issue with the click events not triggering.

MVC #Razor View for Editing Model with Collection [duplicate]

This question already has answers here:
Post an HTML Table to ADO.NET DataTable
(2 answers)
Closed 5 years ago.
I am trying to display and edit a 'Permit Application'.
If it was a piece of paper the top portion would have personal details to fill in.
The bottom portion would be a vertical list of questions with a blank space at the end of each row to write an answer to each question.
So my model is a PermitApplication object which contains with a 'Requestor' object (The applicant) and an array of 'Response' objects which are questions with a string 'Answer' property.
After a lot of thrashing about I am coming to the conclusion maybe what I am trying to does not work under MVC. i.e. Give this sort of model to the view, edit the personal details, fill in the answers to the questions and post the model back.
The view displays OK but when the submit button is pressed the PermitApplication object passed back to the controller only has the personnel details filled in. The returned Responses object is null.
My MVC skills and understanding is limited so my question is 'What is the correct way to tackle this situation? My View (latest attempt) follows:
#model PermitApply.Models.LclPermitApplication
#using (Html.BeginForm())
{
<div class="form-group">
#Html.LabelFor(model => model.Requestor.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Requestor.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Requestor.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<h2>Permit Questions</h2>
<table class="table">
<tr>
<th>
Question Id
</th>
<th>Question</th>
<th>QuestionTypeId</th>
</tr>
#foreach (var item in Model.Responses)
{
<tr>
<td>
#Html.DisplayFor(p => item.QuestionId)
</td>
<td>
#Html.DisplayFor(p => item.Question)
</td>
<td>
#Html.DisplayFor(p => item.QuestionTypeId)
</td>
<td>
<div class="col-md-10">
#Html.EditorFor(p => item.Answer, new { id = item.QuestionId })
#Html.ValidationMessageFor(p => item.Answer, "", new { #class = "text-danger" })
</div>
</td>
</tr>
}
</table>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
}
Try updating the foreach loop to below:
#count = 0;
#foreach (var item in Model.Responses)
{
<tr>
<td>
#Html.DisplayFor(p => item.QuestionId)
</td>
<td>
#Html.DisplayFor(p => item.Question)
</td>
<td>
#Html.DisplayFor(p => item.QuestionTypeId)
</td>
<td>
<div class="col-md-10">
#Html.EditorFor(p => item.Answer, new {name="Responses["+count+"].Answer", id = item.QuestionId })
#Html.ValidationMessageFor(p => item.Answer, "", new { #class = "text-danger" })
</div>
</td>
</tr>
count=count+1;
}
Please read MVC model binding to better understand how MVC binds values to send to controllers. Hope this helps.

ASP.NET View IEnumerable Item validation

I have this ASP:NET MVC Razor View which has a IEnumerable as model .
I'm creating a table where each line represents a item from the IEnumerable.
I'm using this code:
#foreach (var item in Model)
{
<tr>
<td>
<input type="checkbox" name="selectedFoo" value="#item.isAdded"
#(Html.Raw(item.isAdded? "checked=\"checked\"" : "")) />
#item.FooName
</td>
<td>
#Html.EditorFor(modelItem=> item.Name, new { htmlAttributes = new { #class = "form-control", style = "width: 70px" } })
#Html.ValidationMessageFor(modelItem=> item.Name, "", new { #class = "text-danger" })
</td>
</tr>
}
My problem is that when I enter an incorrect value for the "Name" property all the other text input get the validation error.
Solutions?
Thank you.
I would remove '#:' from the table elements. Also using the razor syntax I would generate a form tag. That may have something to do with it. Also add the ValidationSummary method.
Is that snippet you posted the complete view?
#using (Html.BeginForm())
{
#Html.ValidationSummary(true, "", new class{#class="text-danger"})
#foreach (var item in Model)
{
<tr>
<td>
<input type="checkbox" name="selectedFoo" value="#item.isAdded"
#(Html.Raw(item.isAdded? "checked=\"checked\"" : "")) />
#item.FooName
</td>
<td>
#Html.EditorFor(modelItem=> item.Name, new { htmlAttributes = new { #class = "form-control", style = "width: 70px" } })
#Html.ValidationMessageFor(modelItem=> item.Name, "", new { #class = "text-danger" })
</td>
</tr>
}
}
If it's a partial view make sure the property 'Name' doesn't exist on any other fields in the view. 'Name' is very generic, perhaps you should rename it something more descriptive. 'FullName', 'ProductName'. ect....
Your foreach loop is generating duplicated name attributes for each textbox, and the ValidationMessageFor() applies to all elements with that name. In addition, you will never be able to bind to you model when you submit your form.
You need to use a for loop or custom EditorTemplate to generate your elements (refer this answer for more detail)
Assuming your model is IList<T>, then
#for(int i = 0; i < Model.Count; i++)
{
#Html.EditorFor(m => m[i].Name, new { htmlAttributes = new { #class = "form-control", style = "width: 70px" } })
#Html.ValidationMessageFor(m => m[i].Name, "", new { #class = "text-danger" })
}
In addition, use the CheckBoxFor() method to generate checkboxes (assumes selectedFoo is typeof bool)
#Html.CheckBoxFor(m => m[i].selectedFoo)
#Html.LabelFor(m => m[i].selectedFoo, Model[i].FooName)
This can be solved by creating another instance of the model solely for validation purpose in the view.
#{YourNameSpace.Models.Model ValidationModel = new YourNameSpace.Models.Model ();}
Than you can use it in the form like this:
<div class="form-group">
<input asp-for="#ValidationModel.PropertyName" name="[0].Name" class="form-control" />
<span asp-validation-for="#ValidationModel.PropertyName" class="text-danger"></span>
</div>
Or using HTML helper:
#Html.ValidationMessageFor(modelItem => ValidationModel.Name, "", new { #class = "text-danger" })

asp net mvc partial view validation

Hi how are you? I'm trying to validate a form in ASP NET MVC.
I have a partial view "Address" that I reuse for some entities, like Company, Person, etc.
My problem is that when I submit the form, only the controls of the father view gets validated, the ones in the partial view don't.
Here's some code I hope u can geive me hand
PERSON VIEW
#model Entities.Person
#using (Html.BeginForm("Create", "Person", FormMethod.Post))
{
<table>
<tr>
<td>
#Html.LabelFor(model => model.FirstName)
<div class="control">
#Html.TextBoxFor(model => model.FirstName, new { #maxlength = 7, #class = "numeric"})
#Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="spacer-short"></div>
</td>
<td>
#Html.LabelFor(model => model.LastName)
<div class="control">
#Html.TextBoxFor(model => model.LastName, new { #maxlength = 7, #class = "numeric"})
#Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="spacer-short"></div>
</td>
</tr>
</table>
#{ Html.RenderAction("Index", "Address", new {id = Model.AddressId});} //Renders the Address form part
<div class="spacer"></div>
<button type="submit" data-button="true" data-button-icon="ui-icon-disk" class="">Create</button>
<button type="button" data-button="true" data-button-icon="ui-icon-circle-close" class="button-cancel">Cancel</button>
}
ADDRESS VIEW
#model Entities.Address
<table>
<tr>
<td>
#Html.LabelFor(model => model.Street)
<div class="control">
#Html.TextBox("Address.Street", Model.Street)
#Html.ValidationMessage("Address.Street")
</div>
<div class="spacer-short"></div>
</td>
<td>
#Html.LabelFor(model => model.Number)
<div class="control">
#Html.TextBox("Address.Number", Model.Number)
#Html.ValidationMessage("Address.Number")
</div>
<div class="spacer-short"></div>
</td>
</tr>
</table>
Then I have some validation metadata ([Required]) for person and address fields
A common mistake using #Html.Partial(...) and expecting validation errors to show up is not passing ViewData to that partial.:
#Html.Partial([ViewName], [EmailAddressObject], ViewData)
Try this:
#Html.EditorFor(Model.Street)
#Html.ValidationMessageFor(Model.Street)
instead of this:
#Html.TextBox("Address.Street", Model.Street)
#Html.ValidationMessage("Address.Street")
Try using Html.Partial(...) instead of Html.RenderAction(...) to render the partial view. This may be suppressing the validations.
Model
İmportant: Manage Nuget Packages
=>> JQuery.Validation
=>> Microsoft.JQueryUnobtrusive.Validation
install.
1) First step
using System.ComponentModel.DataAnnotations;
2)
public int Id { get; set; }
[Required(ErrorMessage = "* Kategori adı boş geçilemez.")]
[DisplayName("Kategori Adı")]
public string CategoryName { get; set; }
[Required(ErrorMessage = "* Kategori açıklaması boş geçilemez.")]
[DisplayName("Kategori Açıklaması")]
public string Description { get; set; }
3)
if (model != null && ModelState.IsValid)
{
var categoryCreate = new Categories
{
//code
};
_CategoriesService.Create(categoryCreate);
}
4)
Add ViewModel
#model Models.CategoryViewModel
After
#Html.TextBoxFor(model => model.CategoryName, new { #class = "form-control input-sm", id = "categoryTitle", #placeholder = "Kategori adını giriniz.", #type= "text", #required=true })
#Html.ValidationMessageFor(model => model.CategoryName, "", new { #class = "error-message" })
#Html.TextBoxFor(model => model.Description, new { #class = "form-control input-sm", id = "categoryArticle", #placeholder = "Kategori açıklamasını giriniz.", #type = "text", #required = true })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "error-message" })
In my case, I was missing
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
Once I put that in my _layout.cshtml file, it started working even with partial views.

Resources