I have a table called SectionUser like:
SectionUser
USER_ID (varchar(255))(Primary Key)
NAME (varchar(255))
Here are sample values:
USER ID | NAME
EVTAB | ELMER TABER
FAYKVIL | FAYK VILLET
I have a create action in controller that can create a section user successfully. My main problem is that when I edit. I can't get the value. So for example, I've entered wrong USER_ID and I want to edit it. The USER_ID is always null. This means that I want to edit my primary key.
Controller:
public ActionResult EditUser(string USER_ID)
{
if (USER_ID == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
SectionUser section = db.SectionUsers.Find(USER_ID);
if (section == null)
{
return HttpNotFound();
}
return View(section);
}
View(cshtml)
#using (Html.BeginForm("EditUser", "Admin", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Section</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.USER_ID)
<div class="form-group">
#Html.LabelFor(model => model.USER_ID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.USER_ID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.USER_ID, "", 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>
<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>
}
View(Index)
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.USER_ID)
</th>
<th>
#Html.DisplayNameFor(model => model.NAME)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.USER_ID)
</td>
<td>
#Html.DisplayFor(modelItem => item.NAME)
</td>
<td>
#Html.ActionLink("Edit", "EditUser", new { id = item.USER_ID.ToString().Trim() }) |
#Html.ActionLink("Details", "DetailsUser", new { id = item.USER_ID }) |
#Html.ActionLink("Delete", "DeleteUser", new { id = item.USER_ID })
</td>
</tr>
}
</table>
So my issue here is that the parameters I'm using on index.cshtml is wrong. This is the old code:
#Html.ActionLink("Edit", "EditUser", new { id = item.USER_ID.ToString().Trim() })
New Code:
#Html.ActionLink("Edit", "EditUser", new { USER_ID = item.USER_ID.ToString().Trim() })
As you can see in my EditUser Action, the parameter is string USER_ID.
Related
Basically I wanted to display foreign key fields in asp.net cshtml. I have two tables roles and admin respectively. The foreign key relationship shows that for every admin there is a Role which has to be set.
I have done the part of adding role using role name. But when it comes to deleting or updating and such functionality I am not able to figure out the way to display the role name or other role details instead of roleId. I understand the concept of the doing, yet I do not get the right answer in asp.net mvc.
The following code for the cshtml, where I wanted to show the role name instead of role id.
#model IEnumerable<FastFactsTestPortalMVCApp.Models.Administrator>
#{
ViewBag.Title = "ViewAdmin";
Layout = "~/Views/Shared/_LayoutAdmin.cshtml";
}
<h2>ViewAdmin</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.AdminId)
</th>
<th>
#Html.DisplayNameFor(model => model.AdminFirstName)
</th>
<th>
#Html.DisplayNameFor(model => model.AdminLastName)
</th>
<th>
#Html.DisplayNameFor(model => model.AdminEmail)
</th>
<th>
#Html.DisplayNameFor(model => model.AdminUserName)
</th>
<th>
#Html.DisplayNameFor(model => model.AdminPassword)
</th>
<th>
#Html.DisplayNameFor(model => model.AdminContactNumber)
</th>
<th>
#Html.DisplayNameFor(model => model.AdminDesignation)
</th>
<th>
#Html.DisplayNameFor(model => model.AdminRoleId)
</th>
<th>
#Html.DisplayNameFor(model => model.CreatedAt)
</th>
<th>
#Html.DisplayNameFor(model => model.UpdatedAt)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.AdminId)
</td>
<td>
#Html.DisplayFor(modelItem => item.AdminFirstName)
</td>
<td>
#Html.DisplayFor(modelItem => item.AdminLastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.AdminEmail)
</td>
<td>
#Html.DisplayFor(modelItem => item.AdminUserName)
</td>
<td>
#Html.DisplayFor(modelItem => item.AdminPassword)
</td>
<td>
#Html.DisplayFor(modelItem => item.AdminContactNumber)
</td>
<td>
#Html.DisplayFor(modelItem => item.AdminDesignation)
</td>
<td>
#Html.DisplayFor(modelItem => item.AdminRoleId)
</td>
<td>
#Html.DisplayFor(modelItem => item.CreatedAt)
</td>
<td>
#Html.DisplayFor(modelItem => item.UpdatedAt)
</td>
<td>
#Html.ActionLink("Update", "UpdateAdmin", item) |
#Html.ActionLink("Delete", "DeleteAdmin", item)
</td>
</tr>
}
</table>
The below code is for the the admin controller method - ViewAdmin:
public ActionResult ViewAdmin()
{
List<Models.Administrator> administrators = new List<Models.Administrator>();
FastFactsTestPortalMapper<Administrator, Models.Administrator> mapobj = new FastFactsTestPortalMapper<Administrator, Models.Administrator>();
FastFactsTestPortalRepository repObj = new FastFactsTestPortalRepository();
var lstEntityAdmins = repObj.GetAdministrators();
foreach(var admin in lstEntityAdmins)
{
administrators.Add(mapobj.Translate(admin));
}
return View(administrators);
}
Like wise when I update, the cshtml for the update functionality is :
#model FastFactsTestPortalMVCApp.Models.Administrator
#{
ViewBag.Title = "UpdateAdmin";
Layout = "~/Views/Shared/_LayoutAdmin.cshtml";
}
<h2 class="text-center">Update Admin</h2>
#using (Html.BeginForm("SaveUpdatedAdmin","Admin"))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Administrator</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.AdminId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AdminId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AdminId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AdminFirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AdminFirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AdminFirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AdminLastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AdminLastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AdminLastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AdminEmail, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AdminEmail, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AdminEmail, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AdminUserName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AdminUserName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AdminUserName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AdminPassword, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AdminPassword, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AdminPassword, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AdminContactNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AdminContactNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AdminContactNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AdminDesignation, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AdminDesignation, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AdminDesignation, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AdminRoleId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AdminRoleId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AdminRoleId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CreatedAt, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CreatedAt, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CreatedAt, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UpdatedAt, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UpdatedAt, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UpdatedAt, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Update" class="btn" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "ViewAdmin")
</div>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
The controller method for the update functionality is
public ActionResult UpdateAdmin(Models.Administrator administrator)
{
var admindetails = administrator;
return View(administrator);
}
public ActionResult SaveUpdatedAdmin(Models.Administrator administrator)
{
if (ModelState.IsValid)
{
try
{
FastFactsTestPortalRepository repObj = new FastFactsTestPortalRepository();
FastFactsTestPortalMapper<Models.Administrator, Administrator> mapObj = new FastFactsTestPortalMapper<Models.Administrator, Administrator>();
var status = repObj.UpdateAdmin(mapObj.Translate(administrator));
if (status)
{
return RedirectToAction("ViewAdmin");
}
else
{
return View("Error");
}
}
catch (Exception)
{
return View("Error");
}
}
return View("UpdateAdmin", administrator);
}
The Output which I get is :
AdminId AdminFirstName AdminLastName AdminEmail AdminUserName AdminPassword AdminContactNumber AdminRoleId
1 Srinivas Muralidharan sm1043#gmail.com admin admin 09677299116 1
I want to change the AdminRoleId to RoleName : Administrator which is already in the database. Also I wanted to keep the change for all the other functionalities.
Kindly could you explain how to come over such problems?
I am trying to create a form using a table. I have a total of 7 fields. What I am hoping to accomplish is have 3 fields on one row, 3 fields on the second row and the last row would be the last field extended. I tried using colspan however the editorfor box for NextAction is not extending all the way. There is a margin on the right hand side of this field. I've tried creating a CSS class to take away the margin however that did not work as well.
How can I get it so that the NextAction field extends all the way to the last column?
Below I've added my code for the last 2 rows of my table.
<table>
<tr>
<td>
#Html.LabelFor(model => model.Customer, htmlAttributes: new { #class = "control-label labelpadding" })
</td>
<td style="width:300px">
#Html.EditorFor(model => model.Customer, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Customer, "", new { #class = "text-danger" })
</td>
<td>
#Html.LabelFor(model => model.Principal, htmlAttributes: new { #class = "control-label col-md-2" })
</td>
<td style="width:300px">
#Html.EditorFor(model => model.Principal, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Principal, "", new { #class = "text-danger" })
</td>
<td>
#Html.LabelFor(model => model.Product, htmlAttributes: new { #class = "control-label labelpadding" })
</td>
<td>
#Html.EditorFor(model => model.Product, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Product, "", new { #class = "text-danger" })
</td>
</tr>
<tr>
<td>
#Html.LabelFor(model => model.Status, htmlAttributes: new { #class = "control-label labelpadding" })
</td>
<td>
#Html.DropDownListFor(m => m.Status, new SelectList(ViewBag.Status, "Status", "Text"), new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Status, "", new { #class = "text-danger" })
</td>
<td>
#Html.LabelFor(model => model.Value, htmlAttributes: new { #class = "control-label labelpadding" })
</td>
<td>
#Html.EditorFor(model => model.Value, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Value, "", new { #class = "text-danger" })
</td>
<td>
#Html.LabelFor(model => model.FollowUpDate, htmlAttributes: new { #class = "control-label labelpadding" })
</td>
<td>
<div>
<div class="input-group date" data-provide="datepicker">
#Html.EditorFor(model => model.FollowUpDate, new { htmlAttributes = new { #class = "form-control" } })
<div class="input-group-addon">
<span class="glyphicon glyphicon-th"></span>
</div>
</div>
</div>
</td>
</tr>
<tr>
<td>
#Html.LabelFor(model => model.NextAction, htmlAttributes: new { #class = "control-label labelpadding" })
</td>
<td colspan="5">
#Html.EditorFor(model => model.NextAction, new { htmlAttributes = new { #class = "form-control ", #style = "margin-right: 0 !important;"} })
#Html.ValidationMessageFor(model => model.NextAction, "", new { #class = "text-danger" })
</td>
</tr>
</table>
Since you have Bootstrap enabled on your project, use Bootstrap's CSS class w-100. This class will make an element it is applied to have have 100% width. Here is the updated EditorFor line with that class added:
#Html.EditorFor(model => model.NextAction, new { htmlAttributes = new { #class = "form-control w-100"} })
If that doesn't work, you likely have something else overriding it. Check your other style sheets and the HTML that is rendered in your browser.
I want to export my Viewmodel from my view to my controller which is receiving it in a method, this is my view:
#using Resources
#model MyProject.ViewModel.CertificationViewModel
#{
ViewBag.Title = Resources.titleCertificationList;
#section css
{
<link href="#Url.Content("~/layout/css/stylesformador.css")" rel="stylesheet" />
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
}
}
<div class="mainblock">
<div class="block-group">
<div class="ttitle title">#HIQResources.titleEdit</div>
</div>
#using (Html.BeginForm("Edit", "Certification", FormMethod.Post, new { id = "form1" }))
{
#Html.AntiForgeryToken()
<div class="md-content">
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.pdf, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#*<input type="file" name="file" />*#
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control inputForm", #type="file" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Code, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.EditorFor(model => model.Code, new { htmlAttributes = new { #class = "form-control inputForm", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.Code, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SelectedEntityId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.DropDownListFor(model => model.SelectedEntityId, Model.EntitiesDrop, htmlAttributes: new { #class = "form-control inputForm" })
#Html.HiddenFor(model => model.SelectedEntityId)
#Html.ValidationMessageFor(model => model.SelectedEntityId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StatusId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.DropDownListFor(model => model.StatusId, Model.StatusDrop, htmlAttributes: new { #class = "form-control inputForm" })
#Html.HiddenFor(model => model.StatusId)
#Html.ValidationMessageFor(model => model.StatusId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Result, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.EditorFor(model => model.Result, new { htmlAttributes = new { #class = "form-control inputForm" } })
#Html.ValidationMessageFor(model => model.Result, "", 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-8">
#Html.EditorFor(model => model.Date, new { htmlAttributes = new { #class = "form-control inputForm" } })
#Html.ValidationMessageFor(model => model.Date, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Observation, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.EditorFor(model => model.Observation, new { htmlAttributes = new { #class = "form-control inputForm" } })
#Html.ValidationMessageFor(model => model.Observation, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-1">
<div class="col-md-8">
<table class="table table-bordered">
<tr>
<th class="col-md-2">
#Html.DisplayNameFor(model => model.FileName)
</th>
<th class="col-md-2">Ficheiro</th>
</tr>
#foreach (var item in Model.teste)
{
<tr>
<td>
#if (item.FileName == null)
{
<h5>Não existem ficheiros para esta certificação.</h5>
}
else
{
#Html.DisplayFor(modelItem => item.FileName)
}
</td>
<td>
#if (item.FileName == null)
{
<h5>Não existem ficheiros para esta certificação.</h5>
}
else
{
Download
#*Delete*#
<input type="submit" value="Edit" id="Delete" class="btn btn-default btn-sm btn-detail" />
}
#*#Html.ActionLink("Download", "Certification", "Download", new { id = Model.Id })*#
</td>
</tr>
}
</table>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-8">
<input type="submit" value="#HIQResources.buttonSave" class="btn btn-default btn-sm btn-detail" />
#Html.ActionLink(HIQResources.buttonBack, "CertificationList", new { id = Model.StudentId, nome = Model.StudentName }, new { #class = "btn btn-default btn-sm btn-edit" })
</div>
</div>
</div>
</div>
}
</div>
#section Scripts {
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/HIQTrainingScripts/Certification/Edit.js"></script>
<script>
$("#Date").datepicker({ dateFormat: 'yy/mm/dd' });
$("#Delete").click(function () {
var vm = $('#Model').serialize();
alert(vm)
var token = $('input[name="__RequestVerificationToken"]').val();
$.ajax({
url: "/Certification/Edit",
type: "POST",
data: {
__RequestVerificationToken: token,
vm: vm,
click: "deu",
},
sucess: function (result) {
alert("sucess");
}
});
});
</script>
}
This is the method in my controller:
[Authorize(Roles = "Admin, Staff")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(CertificationViewModel vm, string click) {
if (click == "deu")
{
int lol = _servicesFactory.GetService<ICertificationManager>().DeleteFile(vm, GetLoggedUser());
return View(vm);
}
}
The value of my ViewModel comes always as null to my Jquery variable and I don't know why, because it should come with the info from the view to the controller in order for me, to execute my task.
Am I missing something ?
I am doing my MVC application. I have a view that gets data from another view. This view is a form to fill.
public ActionResult AddGroupsQty(int qty, int id)
{
var model = new AddGroupsQtyViewModel();
model.subject_id = id;
model.qty = qty;
ClassDeclarationsDBEntities1 entities1=new ClassDeclarationsDBEntities1();
var subj = entities1.Subjects
.Where(b => b.class_id == model.subject_id)
.FirstOrDefault();
model.subject_name = subj.name;
if (ModelState.IsValid)
{
int maxId = 0;
int total = 0;
total = entities1.Groups.Count();
if (total == 0)
{
maxId = 0;
}
else
{
maxId = entities1.Groups.Max(u => u.group_id);
}
for (int i = 0; i < qty; i++)
{
var teacher = entities1.Users
.Where(b => b.email.Replace(" ", String.Empty) == model.teacher_emails[i].Replace(" ", String.Empty))
.FirstOrDefault();
var group=new Models.Group(id, maxId+1, model.group_names[i], teacher.user_id);
}
return RedirectToAction("OperationSuccess", "Account");
}
return View(model);
}
View model:
public class AddGroupsQtyViewModel
{
public int qty { get; set; }
public int subject_id { get; set; }
public string subject_name { get; set; }
[Required]
[Display(Name = "Name of group")]
public List<string> group_names { get; set; }
[Required]
[Display(Name = "Email of teacher")]
public List<string> teacher_emails { get; set; }
}
And finally my view:
#using System.IdentityModel.Configuration
#using System.Web.UI.WebControls
#model ClassDeclarationsThsesis.Models.AddGroupsQtyViewModel
#{
ViewBag.Title = "AddGroupsQty";
}
<h2>Add Groups to #Model.subject_name</h2>
#if (Model != null)
{
using (Html.BeginForm("AddGroupsQty", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Insert data</h4>
<hr />
<table>
<tr>
<th>
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.group_names, new { #class = "col-md-2 control-label" })
</div>
</th>
<th>
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.teacher_emails, new { #class = "col-md-2 control-label" })
</div>
</th>
</tr>
#for (int i = 0; i < Model.qty; i++)
{
<tr>
<th>
#Html.TextBoxFor(m => m.group_names[i], new { #class = "form-control" })
</th>
<th>
#Html.TextBoxFor(m => m.teacher_emails[i], new { #class = "form-control" })
</th>
</tr>
}
</table>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Submit" />
</div>
</div>
}
}
What more or less it does is it takes qty and generates a table for this many rows. Then, the rows have text boxes to fill in, which should represent data from my View model. However, when I submit, I get such error:
The parameters dictionary contains a null entry for parameter 'qty' of
non-nullable type 'System.Int32' for method
'System.Web.Mvc.ActionResult AddGroupsQty(Int32, Int32)' in
'ClassDeclarationsThsesis.Controllers.AccountController'. An optional
parameter must be a reference type, a nullable type, or be declared as
an optional parameter. Nazwa parametru: parameters
How do I go about this problem?
You are not passing any value for qty after the form submission.
#Html.EditorFor(m => m.qty, new { #class = "form-control" })
#Html.HiddenFor(m=>m.id)
or
#using System.IdentityModel.Configuration
#using System.Web.UI.WebControls
#model ClassDeclarationsThsesis.Models.AddGroupsQtyViewModel
#{
ViewBag.Title = "AddGroupsQty";
}
<h2>Add Groups to #Model.subject_name</h2>
#if (Model != null)
{
using (Html.BeginForm("AddGroupsQty", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.HiddenFor(m=>m.qty) <%-- qty will be found my the controller after form submission --%>
#Html.HiddenFor(m=>m.id) <%-- id will also be found my the controller after form submission --%>
#Html.AntiForgeryToken()
<h4>Insert data</h4>
<hr />
<table>
<tr>
<th>
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.group_names, new { #class = "col-md-2 control-label" })
</div>
</th>
<th>
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.teacher_emails, new { #class = "col-md-2 control-label" })
</div>
</th>
</tr>
#for (int i = 0; i < Model.qty; i++)
{
<tr>
<th>
#Html.TextBoxFor(m => m.group_names[i], new { #class = "form-control" })
</th>
<th>
#Html.TextBoxFor(m => m.teacher_emails[i], new { #class = "form-control" })
</th>
</tr>
}
</table>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Submit" />
</div>
</div>
}
}
I have faced a problem which is can't save the record into the database. I have 3 model in one view. I have done the view and getting error about this
An exception of type 'System.Data.Entity.Validation.DbEntityValidationException' occurred in EntityFramework.dll but was not handled in user code
Additional information: Validation failed for one or more entities.
See 'EntityValidationErrors' property for more details.
here is my view
<div class="container">
<div class="row">
<div class="col-lg-12 management-title">
<h1>Create New Invoice</h1>
</div>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<form>
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.CompanyID, "CompanyID",new { #Name="CompanyID"})
#Html.DropDownList("CompanyID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.PurchaseInvoiceTable.CompanyID , "", new { #class = "text-danger" })
</div>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" href="#bill_to_company">Company Details</a>
</h4>
</div>
<div id="bill_to_company" class="panel-collapse collapse in wrapper-company-details">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.CompanyName)
#Html.TextBoxFor(model => model.PurchaseInvoiceTable.CompanyName, new { #class = "form-control" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.CompanyAddress)
#Html.TextAreaFor(model => model.PurchaseInvoiceTable.CompanyAddress, new { #class = "form-control golbal_textarea" })
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.startdate)
#Html.TextBoxFor(model => model.PurchaseInvoiceTable.startdate, new { #class = "form-control", #Value = #DateTime.Now.ToString() })
</div>
<div class="form-group">
</div>
</div>
</div>
</div>
</div>
<h2>Product List</h2>
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" href="#product_list">Product List</a>
</h4>
</div>
<div id="product_list" class="panel-collapse collapse in input_fields_wrap">
<div class="panel-group" id="accordion">
<div class="panel panel-default">
<div class="panel panel-default product_wrapper">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#product' + x + '">Product</a>
</h4>
</div>
<div id="product'+x+'" class="panel-collapse collapse in">
<div class="panel-group">
<div class="panel panel-default">
<div class="col-lg-12">
<div class="col-lg-3">
<label>Product</label>
#Html.TextAreaFor(model => model.PurchaseInvoiceDetailsTable.Product)
</div>
<div class="col-lg-6">
<label>Description</label>
#Html.TextAreaFor(model => model.PurchaseInvoiceDetailsTable.ProductDescription)
</div>
'<div class="col-lg-2 form-group">
<label>Price</label>
#Html.TextBoxFor(model => model.PurchaseInvoiceDetailsTable.Price)
</div>
</div>
</div>
</div>
</div>
cancel
</div>
</div>
</div>
</div>
</div>
</div>
<button class="add_field_button btn btn-primary pull-right">Add More Fields</button>
<div class="wrapper-company-details">
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.Remark)
#Html.TextAreaFor(model => model.PurchaseInvoiceTable.Remark, new { #class = "form-control", #style = "resize:none;" })
#Html.ValidationMessageFor(model => model.PurchaseInvoiceTable.Remark, "", new { #class = "text-danger" })
</div>
<h1>Payment Term Area</h1>
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" href="#payment_term_collapse">Payment Term</a>
</h4>
</div>
<div id="payment_term_collapse" class="payment_term_area panel-collapse collapse in">
<table class="table table-bordered">
<tr style="background-color:black; color:white;">
<th style="width:70%;">
<input type="text" class="form-control" id="payment_term" placeholder="Type how many terms client want" />
</th>
<th style="width:30%;">
<button class="btn btn-default" id="add_payment_terms">Add</button>
</th>
</tr>
</table>
<table class="table table-bordered">
<tr style="background-color:black; color:white;">
<th style="width:70%;">
Payment Term
</th>
<th style="width:30%;">
Amount
</th>
</tr>
<tr style="background-color:black; color:white;">
<th style="text-align:right;">
Discount
</th>
<th>
#Html.TextBoxFor(model => model.PurchaseInvoiceTable.Discount, new { #class = "form-control discount price_textbox", #id = "discount", #Value = "0" })
</th>
</tr>
<tr style="background-color:black; color:white;">
<th style="text-align:right;">
Total
</th>
<th>
#Html.TextBoxFor(model => model.PurchaseInvoiceTable.Subtotal, new { #class = "form-control price_textbox total", #id = "totval", #Value = "0" })
</th>
</tr>
</table>
<div id="payment_term_area">
<h2>Payment Terms</h2>
<div class="payment_term_wrapper" style="padding:0; margin:0;">
<table class="table table-bordered" style="width:95%;">
<tr style="background-color:black; color:white;" class="payment_term_wrapper">
<th style="width:70%;">
<input class="pull-right payment_terms_label_input" style="background-color:black; color:white;"></input>
</th>
<th style="width:30%;">
#Html.TextBoxFor(model => model.PaymentTerm.Amount)
</th>
</tr>
X
</table>
</div>
</div>
<table class="table table-bordered">
<tr style="background-color:black; color:white;">
<th style="text-align:right; width:70%;">
Last Payment
</th>
<th style="width:30%;">
#Html.TextBoxFor(model => model.PurchaseInvoiceTable.Total, new { #class = "form-control price_textbox", #id = "lastpayment", #Value = "0" })
</th>
</tr>
</table>
</div>
</div>
</div>
</div>
<div class="col-lg-12">
</div>
<div class="col-lg-12">
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.Category, "Category")
#Html.DropDownList("Category", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.PurchaseInvoiceTable.Category, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.Method)
#Html.DropDownListFor(model => model.PurchaseInvoiceTable.Method, new List<SelectListItem>
{
new SelectListItem() {Text = "Cash", Value="Cash"},
new SelectListItem() {Text = "Cheque", Value="Cheque"},
new SelectListItem() {Text = "Bank Transfer", Value="BankTransfer"}
}, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.PurchaseInvoiceTable.Method, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.PaymentTerm, "PaymentTerm", htmlAttributes: new { #class = "control-label col-md-2" })
#Html.DropDownListFor(model => model.PurchaseInvoiceTable.PaymentTerm, new List<SelectListItem>
{
new SelectListItem() {Text = "1", Value="1"},
new SelectListItem() {Text = "2", Value="2"},
new SelectListItem() {Text = "3", Value="3"}
}, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.PurchaseInvoiceTable.PaymentTerm, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.HiddenFor(model => model.PurchaseInvoiceTable.Status, new { #class = "form-control", #Value = "Active" })
#Html.HiddenFor(model => model.PurchaseInvoiceDetailsTable.Status, new { #class = "form-control", #Value = "Active" })
#Html.HiddenFor(model => model.PaymentTerm.Status, new { #class = "form-control", #Value = "Active" })
</div>
<div class="form-group">
#Html.HiddenFor(model => model.PurchaseInvoiceTable.first_created, new { #class = "form-control", #Value = #DateTime.Now.ToString() })
#Html.HiddenFor(model => model.PurchaseInvoiceDetailsTable.first_created, new { #class = "form-control", #Value = #DateTime.Now.ToString() })
#Html.HiddenFor(model => model.PaymentTerm.first_created, new { #class = "form-control", #Value = #DateTime.Now.ToString() })
</div>
<div class="form-group">
#Html.HiddenFor(model => model.PurchaseInvoiceTable.first_created_by, new { #class = "form-control", #Value = #Session["Username"].ToString() })
#Html.HiddenFor(model => model.PurchaseInvoiceDetailsTable.first_created_by, new { #class = "form-control", #Value = #Session["Username"].ToString() })
#Html.HiddenFor(model => model.PaymentTerm.first_created_by, new { #class = "form-control", #Value = #Session["Username"].ToString() })
</div>
<div class="form-group">
#Html.HiddenFor(model => model.PurchaseInvoiceTable.last_updated, new { #class = "form-control", #Value = #DateTime.Now.ToString() })
#Html.HiddenFor(model => model.PurchaseInvoiceDetailsTable.last_updated, new { #class = "form-control", #Value = #DateTime.Now.ToString() })
#Html.HiddenFor(model => model.PaymentTerm.last_updated, new { #class = "form-control", #Value = #DateTime.Now.ToString() })
</div>
<div class="form-group">
#Html.HiddenFor(model => model.PurchaseInvoiceTable.last_updated_by, new { #class = "form-control", #Value = #Session["Username"].ToString() })
#Html.HiddenFor(model => model.PurchaseInvoiceDetailsTable.last_updated_by, new { #class = "form-control", #Value = #Session["Username"].ToString() })
#Html.HiddenFor(model => model.PaymentTerm.last_updated_by, new { #class = "form-control", #Value = #Session["Username"].ToString() })
</div>
<div class="form-group">
<div>
<input type="submit" value="Create" class="btn btn-primary pull-right" />
#Html.ActionLink("Back", "Index", null, new { #class = "btn btn-small btn-danger pull-right", #style = "margin-right:2%;" })
</div>
</div>
</div>
</form>
}
</div>
</div>
here is my controller
public ActionResult Create()
{
ViewBag.CompanyID = new SelectList(db.SupplierTables, "SupplierID", "SupplierID");
ViewBag.Product = new SelectList(db.ProductTables, "ProductID", "ProductID");
ViewBag.Category = new SelectList(db.CategoryTables, "CategoryID", "CategoryID");
ViewBag.PaymentTerm = new SelectList(db.PaymentTerms, "TermID", "TermID");
return View();
}
[HttpPost]
public ActionResult Create([Bind(Include = "PurchaseInvoiceTable,PurchaseInvoiceDetailsTable,PaymentTerm")]InvoiceWrapper model)
{
if (ModelState.IsValid)
{
db.PurchaseInvoiceTables.Add(model.PurchaseInvoiceTable);
db.PurchaseInvoiceDetailsTables.Add(model.PurchaseInvoiceDetailsTable);
db.PaymentTerms.Add(model.PaymentTerm);
db.SaveChanges();
//model.PurchaseInvoiceTable.PurchaseInvoiceID = model.PurchaseInvoiceDetailsTable.InvoiceID = model.PaymentTerm.InvoiceID;
return RedirectToAction("Index");
}
ViewBag.CompanyID = new SelectList(db.SupplierTables, "SupplierID", "SupplierID");
ViewBag.Product = new SelectList(db.ProductTables, "ProductID", "ProductID");
ViewBag.Category = new SelectList(db.CategoryTables, "CategoryID", "CategoryID");
ViewBag.PaymentTerm = new SelectList(db.PaymentTerms, "TermID", "TermID");
return View(model);
}
The exception you are getting means that one or more of the entities properties that you are trying to save is not valid. e.g. The column is defined as not null and the property you are trying to save is null.
In order to see the validation errors you can use this:
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Trace.TraceInformation("Property: {0} Error: {1}",
validationError.PropertyName,
validationError.ErrorMessage);
}
}
}
credits