I have simple form a dropdown list and a textbox. When the page is loaded textbox is disabled. If 'Other' is selected from dropdown list, then textbox is enabled and I add 'required' rule to textbox as I don't want user to enter something in the text box. When 'Other' is selected and if Create button is clicked, I can see validation error message but I cannot remove that message after user has typed something in the empty textbox. Here is how it looks:
Here is my model:
using System.ComponentModel.DataAnnotations;
namespace validatetextbox.Models
{
public class Manager
{
public int Id { get; set; }
[Required]
public string City { get; set; }
[Display(Name = "Other City")]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string OtherCity { get; set; }
}
}
My Controller method is
// GET: Managers/Create
public ActionResult Create()
{
//populate Gender dropdown
List<SelectListItem> c = new List<SelectListItem>();
c.Add(new SelectListItem { Text = "-- Please Select --", Value = "" });
c.Add(new SelectListItem { Text = "New York", Value = "New York" });
c.Add(new SelectListItem { Text = "Miami", Value = "Miami" });
c.Add(new SelectListItem { Text = "Other", Value = "Other" });
ViewBag.Cities = c;
return View();
}
My view is as follows:
#model validatetextbox.Models.Manager
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Manager</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.City, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.City, ViewBag.Cities as List<SelectListItem>, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.City, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OtherCity, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OtherCity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.OtherCity, "", 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" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(document).ready(function () {
$('#OtherCity').prop('disabled', true);
$('#City').change(function () {
if ($('#City option:selected').text() != 'Other') {
$("#OtherCity").rules("remove", "required");
$('#OtherCity').prop('disabled', true);
} else {
$('#OtherCity').prop('disabled', false)
$("#OtherCity").rules("add", "required");
}
});
});
</script>
}
To keep your existing code - you can remove the rules from the text box on document ready. Also - side note - keep quotation marks consistent.
<script type="text/javascript">
$(document).ready(function () {
$('#OtherCity').prop('disabled', true);
// Remove any rules
$('#OtherCity').rules("remove");
$('#City').change(function () {
if ($('#City option:selected').text() != 'Other') {
//Also tidy up `"` to `'`
$('#OtherCity').rules("remove", "required");
$('#OtherCity').prop('disabled', true);
} else {
$('#OtherCity').prop('disabled', false)
//Also tidy up `"` to `'`
$('#OtherCity').rules("add", "required");
}
});
});
</script>
Another thing you could try is - add the class optional to the editor - the label will display and the visibility and validation requirement will be controlled by the JS:
<div class="form-group">
#Html.LabelFor(model => model.OtherCity, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10 optional">
#Html.EditorFor(model => model.OtherCity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.OtherCity, "", new { #class = "text-danger" })
</div>
</div>
$(document).ready(function () {
// This will hide the field
$('.optional').hide();
// This makes the value optional
$('#OtherCity').attr("data-val", "false");
$('#City').change(function () {
if ($('#City option:selected').text() == 'Other') {
// Show the text editor
$('.optional').show();
// This makes the value required
$('#OtherCity').attr("data-val", "true");
} else {
$('.optional').hide();
$('#OtherCity').attr("data-val", "false");
}
});
});
Related
I am trying to populate/fill a dropdown but I can't seem to get the values I need.
The "Employee Name" dropdown does not get populated while the "Platform Group" one does.
For "Employee Name" I use POST because this method is called by another VIEW in the software so I'd rather not change it.
I tried everything I could but the values will not show in the console or in the UI.
What am I missing?
Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace FXM.BO.ViewModels
{
public class NewAffiliateViewModel
{
public NewAffiliateViewModel()
{
}
public int Id { get; set; }
public string AffiliateName { get; set; }
public string Email { get; set; }
public int Employee { get; set; }
public int MT4Group { get; set; }
}
}
View
#model FXM.BO.ViewModels.NewAffiliateViewModel
#{
ViewBag.Title = "CreateAffiliate";
Layout = "~/Views/Shared/_LoggedInLayout.cshtml";
}
<h2>Create Affiliate</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4 class="hidden">NewAffiliateViewModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.AffiliateName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AffiliateName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AffiliateName, "", 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.Employee, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee, "", new { #class = "text-danger" })
</div>
</div>*#
#*<div class="form-group">
#Html.LabelFor(model => model.MT4Group, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MT4Group, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MT4Group, "", new { #class = "text-danger" })
</div>
</div>*#
<div class="form-group">
<label class="control-label col-md-2">
#FXM.BO.Strings.T("employeeName") <span class="required">
#***#
</span>
</label>
#*<div class="col-md-4 fieldPositionCol4 select2-bootstrap-prepend">*#
<div class="col-md-10 ">
#Html.DropDownListFor(x => x.Employee, new SelectList(new Dictionary<string, string>(), "Key", "Value"), #FXM.BO.Strings.T("ddl_select_option"), new { #class = "form-control select2-allow-clear", #placeholder = "Select Symbols" })
<span class="help-block">
#FXM.BO.Strings.T("lbl_employee_description")
</span>
</div>
<img id="tpLoader" src="~/Content/images/ajax-loader.gif" class="hidden" />
</div>
<div class="form-group">
<label class="control-label col-md-2">
#FXM.BO.Strings.T("lbl_Bo_TradAcc_PlatformGroup") <span class="required">
#***#
</span>
</label>
#*<div class="col-md-4 fieldPositionCol4 select2-bootstrap-prepend">*#
<div class="col-md-10 ">
#Html.DropDownListFor(x => x.MT4Group, new SelectList(new Dictionary<string, string>(), "Key", "Value"), #FXM.BO.Strings.T("ddl_select_option2"), new { #class = "form-control select2-allow-clear", #placeholder = "Select Symbols" })
<span class="help-block">
#FXM.BO.Strings.T("platform_group_description")
</span>
</div>
<img id="tpLoader" src="~/Content/images/ajax-loader.gif" class="hidden" />
</div>
#*Create button*#
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" value="Create" class="btn btn-default" id="create-affiliate-button" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
<script type="text/javascript" src="/Scripts/CustomScripts/Common/form-helpers.js"></script>
#*<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>*#
<script type="text/javascript">
// document.ready function
$(function () {
refreshGroups();
// selector has to be . for a class name and # for an ID
$('#create-affiliate-button').click(function (e) {
//e.preventDefault(); // prevent form from reloading page
console.log("blahblahblah");
var b = $("form").serialize();
//var a = $("form").serializeArray();
console.log("formvalues", b);
$.ajax({
url: "/en/AjaxUI/CreateAffiliate",
type: "GET",
dataType: "json",
data: b,
},
//error: function (jqXHR, exception) {
// failMessage();
//}
});
});
});
function refreshGroups() {
var pltf = "MT4_LIVE";
var out = $('#MT4Group');
if (pltf != null && pltf !== "") {
$.ajax({
url: '/' + window.currentLangCulture + '/BOLiveForms/GetPlatformGroupByFilter',
data: {
platform: pltf, currency: "", withId : true
},
type: 'GET',
beforeSend: function () {
$('#tpLoader').show();
},
complete: function () {
$('#tpLoader').hide();
},
success: function (data) {
populateDropDown(out, data);
//$('#recomandedGroup').show();
}
});
} else {
out.empty();
out.append($('<option></option>').val('').html(window.defaultSelection));
}
}
//GetEmployeesExcept - Method that populates the Dropdown for EmployeeName
$(function() {
$.validator.addMethod("regxPhone", function(value, element, regexpr) {
return regexpr.test(value);
}),
$.validator.addMethod("regxEmail", function(value) {
return /^([\w!.%+\-])+##([\w\-])+(?:\.[\w\-]+)+$/.test(value);
}),
$.validator.addMethod('validEmail', function(value, element, param) {
return valiEmailAjax($("#Email").val());
});
$('#create-affiliate-button').select2({
theme: "bootstrap",
ajax: {
url: "/en/BOEmployeeAjax/GetEmployeesExcept",
type: "POST",
dataType: "json",
data: function(params) {
return {
emplId: 0,
t: params.term
}
},
processResults: function(data, params) {
return { results: data }
}
},
placeholder: window.selectAnotherSupervisor,
escapeMarkup: function(markup) { return markup; },
minimumInputLength: 0
});
</script>
Method in the Controller (for Employee Name)
[HttpPost]
[OutputCache(CacheProfile = "Cache10mn", Location = OutputCacheLocation.Client, NoStore = true)]
public JsonResult GetEmployeesExcept(int emplId, string t, bool searchByUserId=false)
{
t = string.IsNullOrWhiteSpace(t) ? String.Empty : t;
t = string.IsNullOrWhiteSpace(t) ? String.Empty : t;
if (!searchByUserId)
{
return Json(CrmServices.GetAllEmployees()
.Where(w => w.Id != emplId && string.Format("{1}{0}", w.UserDetails.Fullname, w.Id).ToLower().Contains(t.ToLower()))
.Select(s => new { id = s.Id, text = string.Format("{1} : {0}", s.UserDetails.Fullname, s.Id) }));
}
else
{
return Json(CrmServices.GetAllEmployees()
.Where(w => w.UserDetails != null && int.Parse(w.UserDetails.UserID) != emplId && string.Format("{1}{0}", w.UserDetails.Fullname, w.UserDetails.UserID).ToLower().Contains(t.ToLower()))
.Select(s => new { id = s.UserDetails.UserID, text = string.Format("{1} : {0}", s.UserDetails.Fullname, s.UserDetails.UserID) }));
}
}
method in the Controller (for "Platform Group")
public JsonResult CreateAffiliate(NewAffiliateViewModel newAffiliateViewModel)
{
try
{
var res = BackOfficeServices.BoAddAffiliateUser(newAffiliateViewModel);
//SystemServices.ResendEmail(userId);
return Json("success");
//return Json(null, JsonRequestBehavior.DenyGet);
}
catch (Exception e)
{
throw e;
}
}
Also, when I uncomment the code for the ajax request for "Employee Name", the "Platform group" stops being populated. When I comment it back, the "Platform group" is populated just fine.
Thank you for any response.
You need to search for : "Select2"
Here is site https://select2.org/
Read the guid, its easy
UPDATE 1:
Here is EXAMPLE of code, that you need, man.
My editorfor onChangeEvent isn't working and I can't figure out why.
here is my javascript function
<script type="text/javascript">
function OnChangeEvent() {
alert("value is changed");
var compQty = $('#compQTY').val();
//do other functions here also like change button
//if decrease add below
if (compQty < #Model.comp_qty) {
btn.Attributes.Add("onclick", "clicked(event)");
}
}
<script>
and here is my editorFor
<div class="form-group">
#Html.LabelFor(model => model.comp_qty, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#if (ViewBag.isValid == false)
{
#Html.TextBoxFor(model => model.comp_qty, new { disabled = "disabled", #Value = Model.comp_qty, #readonly = "readonly" })
}
else
{
#Html.EditorFor(model => model.comp_qty, new { htmlAttributes = new { onchange = "OnChangeEvent(this)", min = 0, #class = "form-control", #id = "compQTY" } })
#Html.ValidationMessageFor(model => model.comp_qty, "", new { #class = "text-danger" })
}
</div>
</div>
from what I have googled this should work but it is not. Can anybody help me figure out what I'm missing or what the possible solution is?
I Have a view where I can edit and add new Rows on my SQL called by AddOrEdit. All I need is to press the button Submit after fill/change the fields. It calls my ActionResult on AccountController that brings me a JsonResult and my AJAX function on button click get the JsonResult to fill a Notify.js message to say that the submit was successfully done.
Problem:
When I create a new row, all works how should be but when I update a existing row, the Success message comes to my browser as raw Json.
Controller:
[HttpPost]
public ActionResult AddOrEdit(UserPortal user)
{
using (ModelEntities db = new ModelEntities())
{
try
{
if (user.UserID == 0)
{
db.UserPortals.Add(user);
}
else
{
db.Entry(user).State = EntityState.Modified;
}
db.SaveChanges();
return Json(new { success = true, message = "Submitted Successfully. Redirecting..." }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { success = true, message = ex.Message }, JsonRequestBehavior.AllowGet);
}
}
}
View:
#using (Html.BeginForm("AddOrEdit", "Account", FormMethod.Post, new { onsubmit = "return SubmitForm(this)" }))
{
<form id="AddOrEditUserForm">
#Html.HiddenFor(model => model.UserID)
<div class="form-group">
#Html.LabelFor(model => model.UserEmail, new { #class = "control-label" })
#Html.EditorFor(model => model.UserEmail, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UserEmail)
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserName, new { #class = "control-label" })
#Html.EditorFor(model => model.UserName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UserName)
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserCompany, new { #class = "control-label" })
#Html.EditorFor(model => model.UserCompany, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UserCompany)
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserPosition, new { #class = "control-label" })
#Html.EditorFor(model => model.UserPosition, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserAccessLevel, new { #class = "control-label" })
#Html.EditorFor(model => model.UserAccessLevel, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UserAccessLevel)
</div>
<div class="form-group">
<input type="submit" name="Submit" value="Salvar" class="btn btn-primary" />
</div>
</form>
}
Javascript on View:
function SubmitForm(form) {
$.validator.unobtrusive.parse(form);
if ($(form).valid()) {
$.ajax({
type: "POST",
url: form.action,
data: $(form).serialize(),
success: function (data) {
var delay = 2000; // time in milliseconds
if (data.success) {
$.notify(data.message, {
globalPosition: "top center",
className: "success",
})
setTimeout(function () {
window.location.href = '#Url.Action("AdminUsers", "Account")'; //redirect to the main page after some seconds
}, delay);
}
},
error: function (jqXHR, textStatus, errorThrown) { errorFunction(); },
});
}
return false;
}
Notify.js working when I add a new user:
image 1
When I click on submit button to update a existing user
image 2
What I've tried:
1- I add some console.log on my Submit Function and after if ($(form).valid()) I just don't receive anymore my console.log test. I think the problem is the Function and the ajax inside it.
2- On controller I gave a single JsonResult for each situation: to create I had a message saying "Created Successfully" and It worked but on the message below "Update Successfully" I got the same problem: a raw json on my screen but working perfectly on backend updating the row I requested.
I have a table on which there's an Edit button for every record at the last column.
My goal is to have an editable form on a modal for the record on which the user pressed the Edit button.
In order to accomplish that, I've created a Partial View which i want to be loaded on the modal, but after tons of tries, i cannot get it working. The JS created to compose the partial view URL and loading into the modal seems to have no effect and it's raising the following error:
VM364 ESa31501901:361 Uncaught ReferenceError: ESa31501901 is not
defined
at HTMLAnchorElement.onclick
Note: ESa31501901 is the first parameter passed into the JS function.
This is my intention:
a) Edit() : This method will return all records.
b) EditClientFeature(string ClientID, string WorkProcessID): This method will return a partial view containing the record of a particular client. This method is called when we start editing a client record. The client record is displayed in modal (popup).
c) EditClientFeature(ClientFeatureViewModel model): This method will update the client record.
ClientFeature ViewModel
public class ClientFeatureViewModel
{
public string ClientID { get; set; }
public string WorkProcessID { get; set; }
public int? Certification { get; set; }
public bool? TrackingActive { get; set; }
public string ClientCode { get; set; }
public string ContractNo { get; set; }
public string ProductCode { get; set; }
}
Edit.cshtml
[...]
<tbody>
#foreach (var feature in Model.ClientFeatures)
{
<tr>
<td style="text-align:center"><strong>#feature.WorkProcessId</strong>/td>
<td style="text-align:center">#feature.Certificate</td>
<td style="text-align:center">#feature.TrackingActive</td>
<td style="text-align:center">#feature.ClientCode</td>
<td style="text-align:center">#feature.ContractNo</td>
<td style="text-align:center">#feature.ProductCode</td>
<td>
<i class="glyphicon glyphicon-pencil"></i>
</td>
</tr>
}
</tbody>
[...]
<div class="modal fade" id="ModalClientFeatures">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
×
<h3 class="modal-title">Edit</h3>
</div>
<div class="modal-body" id="ModalBodyDiv">
<!-- Here's where i want to show the partial view-->
</div>
</div>
</div>
</div>
[...]
<script>
function EditCF(ClientID, WorkProcessID) {
var url = "/Admin/EditClientFeature?ClientID=" + ClientID + "?WorkProcessID=" + WorkProcessID;
$("#ModalBodyDiv").load(url, function () {
$("#ModalClientFeatures").modal("show");
})
}
</script>
ClientFeaturepartialView.cshtml
#model Project.Models.ClientFeatureViewModel
<script src="~/Scripts/jquery-3.3.1.js"></script>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<form id="myForm">
<div class="form-horizontal">
<h4>ClientFeatureViewModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.ClientID)
<div class="form-group">
#Html.LabelFor(model => model.WorkProcessID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.WorkProcessID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.WorkProcessID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Certification, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Certification, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Certification, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TrackingActive, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.TrackingActive)
#Html.ValidationMessageFor(model => model.TrackingActive, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ClientCode, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ClientCode, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ClientCode, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ContractNo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ContractNo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ContractNo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProductCode, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ProductCode, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ProductCode, "", 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" />
<a href="#" id="btnSubmit" class="btn btn-success btn-block">
<span>Update</span>
</a>
</div>
</div>
</div>
</form>
}
Controller
public ActionResult EditClientFeature(string ClientID, string WorkProcessID)
{
PMEntities db = new EntityConn().Db;
ClientFeatures ClientFeature = db.ClientFeatures.Where(cf => cf.ClientId == ClientID && cf.WorkProcessId == WorkProcessID).SingleOrDefault();
if (ClientFeature != null) {
ClientFeatureViewModel model = new ClientFeatureViewModel
{
ClientID = ClientFeature.ClientId,
WorkProcessID = ClientFeature.WorkProcessId,
Certification = ClientFeature.Certificate,
TrackingActive = ClientFeature.TrackingActive,
ClientCode = ClientFeature.ClientCode,
ContractNo = ClientFeature.ContractNo,
ProductCode = ClientFeature.ProductCode,
};
return PartialView("ClientFeaturePartialView", model);
}
else { return View("Error"); }
}
[HttpPost]
public ActionResult EditClientFeature(ClientFeatureViewModel model)
{
try
{
PMEntities db = new EntityConn().Db;
if (model.ClientID != null)
{
//update
ClientFeatures ClientFeature = db.ClientFeatures.Where(cf => cf.ClientId == model.ClientID && cf.WorkProcessId == model.WorkProcessID).SingleOrDefault();
ClientFeature.Certificate = model.Certification;
ClientFeature.ClientCode = model.ClientCode;
ClientFeature.ContractNo = model.ContractNo;
ClientFeature.ProductCode = model.ProductCode;
ClientFeature.TrackingActive = model.TrackingActive;
db.SaveChanges();
}
}
catch (Exception ex)
{
throw ex;
}
}
I think your onclick function parameter value is treated as a variable, not a string.
Solution 1:
Try below to pass as string: (Not tested though!)
onclick="EditCF(\'' + #Model.Piva + '\', \'' + #feature.WorkProcessId+ '\')"
Solution 2:
It's best to Attach a click handler after adding a class for your link. And use HTML5 data attributes for storing your value client side.
<i class="glyphicon glyphicon-pencil"></i>
$('.editClient).on('click', function() {
var clientID = $(this).data('ClientID');
var workProcessId = $(this).data('WorkProcessId');
var url = "/Admin/EditClientFeature?ClientID=" + clientID
+ "?WorkProcessID=" + workProcessID;
$("#ModalBodyDiv").load(url, function () {
$("#ModalClientFeatures").modal("show");
})
});
Reference
Hope this helps.
I'm using Entity Framework 7 with ASP.NET MVC 5.
I have some forms that look like this. Clicking on one of the "new" buttons brings up a Bootstrap modal that looks like this. Submitting the modal form adds a new entity to the database before appending its name and primary key to the selectlist.
This works, but if the user changes their mind, the item(s) created via the modal (location in this case) stick around forever. So ideally none of the child items would be created until the main form is finished. While the example only has two simple fields, other data models have more than half a dozen, which may include complex fields of their own (but preventing that wouldn't be a horrible restriction).
So what's the best way to do this, nested divs serialized by JavaScript? Nested divs would also make it easy to allow reordering by the user, which is the end goal.
Does ASP.NET have a better way to handle this?
This feels hacky, but it works.
Using BeginCollectionItem, you can have the modal add hidden input elements to the DOM.
I wrote an action method that returns JSON with the modelstate (valid/invalid) and errors or partial HTML for invalid and valid submissions, respectively. Based on this, JavaScript either adds the errors to the summary or adds the requisite label and hidden inputs to the initial form.
Then have the main form's viewmodel contain an ICollection of your data model, called Contacts in below code, and ASP.NET handles the data binding with no troubles.
Example:
_CollectionItem.cshtml (partial HTML added to main form after valid submission)
#model Project.Models.ContactCreateViewModel
<li>
<div class="collection-item">
#using (Html.BeginCollectionItem("Contacts"))
{
<span class="item-name">#Model.LastName, #Model.FirstName</span> <span class="btn btn-danger delete-item">Delete</span>
#Html.HiddenFor(model => model.FirstName)
#Html.HiddenFor(model => model.LastName)
#Html.HiddenFor(model => model.PhoneNumber)
#Html.HiddenFor(model => model.PhoneExt)
#Html.HiddenFor(model => model.Email)
}
</div>
</li>
_CreateModal.cshtml (partial used for the body of the modal)
#model Project.Models.ContactCreateViewModel
<div class="modal-header">
<button type="button" class="close btn-modal-close" data-dismiss="modal"><i class="fas fa-times"></i></button>
<h4 class="modal-title">New Contact</h4>
</div>
<div class="modal-body">
#using (Html.BeginForm("CreateModal", "Contacts", FormMethod.Post, new { id = "new-contact-form" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummaryPlaceholder()
#* First Name *#
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
#* Last Name *#
<div class="form-group">
#Html.LabelFor(model => model.LastName, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
#* Phone Number *#
<div class="form-group">
#Html.LabelFor(model => model.PhoneNumber, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.PhoneNumber, new { htmlAttributes = new { #class = "form-control phone" } })
#Html.ValidationMessageFor(model => model.PhoneNumber, "", new { #class = "text-danger" })
</div>
</div>
#* Phone Ext *#
<div class="form-group">
#Html.LabelFor(model => model.PhoneExt, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.PhoneExt, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PhoneExt, "", new { #class = "text-danger" })
</div>
</div>
#* Email *#
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
#* SUBMIT *#
<div class="form-group">
<div class="col-md-offset-4 col-md-8">
<input type="submit" value="Create" class="btn btn-success" />
</div>
</div>
</div>
}
</div>
#Scripts.Render("~/Scripts/Custom/ajax-add-collection-item.js")
<script>
$(function () {
ajaxAddCollectionItem("new-contact-form", "contacts", function () {
alertify.success("Added new contact");
})
});
</script>
ajax-add-collection-item.js (capture modal form submission, add _CollectionItem.cshtml to main form)
// Posts form and adds collection item to ul
function ajaxAddCollectionItem(formId, listId, onSuccess = function () { }) {
let $form = $("#" + formId);
$form.submit(function (event) {
event.preventDefault();
$.ajax({
method: "POST",
url: $form.attr("action"),
data: $form.serialize(),
success: function (data) {
let successful = data["success"];
// If form is valid, close modal and append new entry to list
if (successful) {
$("#" + listId).append(data["html"]);
$(".delete-item").click(function (event) {
$(this).closest("li").remove();
});
$(".btn-modal-close").trigger("click");
onSuccess();
}
// If form is not valid, display error messages
else {
displayValidationErrors(data["errors"]);
}
},
error: function (error) {
alert("Dynamic content load failed.");
console.error("Ajax call failed for form: " + $form);
}
});
});
// Populate validation summary
function displayValidationErrors(errors) {
let $ul = $('div.validation-summary-valid.text-danger > ul');
$ul.empty();
$.each(errors, function (i, errorMessage) {
$ul.append('<li>' + errorMessage + '</li>');
});
}
}
ContactsController.cs
public class ContactsController
{
// GET: Contacts/CreateModal
public ActionResult CreateModal()
{
return PartialView("_CreateModal");
}
// POST: Contacts/CreateModal
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> CreateModal(ContactCreateViewModel viewModel)
{
// If form is valid and email does not already exist, send HTML for collection item,
// otherwise send modelstate errors
if (ModelState.IsValid)
{
User user = await UserManager.FindByEmailAsync(viewModel.Email);
if (user == null)
// RenderPartialView returns partial HTML as a string,
// see https://weblog.west-wind.com/posts/2012/May/30/Rendering-ASPNET-MVC-Views-to-String
return Json(new { success = true, html = RenderPartialView("_CollectionItem", viewModel) });
else
ModelState.AddModelError("Email", "Email already exists.");
}
return Json(new { success = false, errors = GetModelStateErrors() });
}
// Actually in base controller class
protected string[] GetModelStateErrors()
{
return ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage).ToArray();
}
}