Bootstrap Switch: On change set specific DropDownList to blank? - jquery-ui

I am using BootStrap Switch to show/hide certain s based on the Switch value. When I need to ensure (for my Controller postback) is that when a switch is made, the DropDownList being hidden has it's value reset to blank or null. I need to ensure that a user can only select a value for Member Organizations or Sponsors, not for both.
I however can't seem to figure out how to reference a specific DropDownList control in my javascript (still fairly new to MVC development). Anyone have thoughts on the matter?
HTML
<div style="margin-bottom: 15px">
<div class="row switchOn">
<div class="editor-label">
#Html.LabelFor(model => model.MemberOrgId, "Organization")
</div>
<div class="editor-field">
#Html.DropDownList("OrganizationId", null, String.Empty, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.MemberOrgId)
</div>
</div>
<div class="row switchOff">
<dliv class="editor-label">
#Html.LabelFor(model => model.SponsorOrgId, "Sponsor")
</dliv>
<div class="editor-field" >
#Html.DropDownList("SponsorId", null, String.Empty, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.SponsorOrgId)
</div>
</div>
</div>
jQuery
<script type="text/javascript">
jQuery(document).ready(function () {
setTimeout(function () { $("#alert").alert('close'); }, 5000);
$('.switchOff').addClass('hide');
});
$.fn.bootstrapSwitch.defaults.onText = 'Member';
$.fn.bootstrapSwitch.defaults.offText = 'Sponsor';
$.fn.bootstrapSwitch.defaults.offColor = 'info';
$.fn.bootstrapSwitch.defaults.animate = false;
//$.fn.bootstrapSwitch.defaults.size = 'large';
$(document).ready(function () {
$('input:checkbox[name="Sponsor-Organization"]').bootstrapSwitch();
});
$('input:checkbox[name="Sponsor-Organization"]').on('switchChange.bootstrapSwitch', function (event, state) {
var checked = state;
if (checked) {
$('.switchOn').removeClass('hide');
$('.switchOff').addClass('hide');
}
else {
$('.switchOff').removeClass('hide');
$('.switchOn').addClass('hide');
}
});
$(document).ready(function () {
$(".btn-danger").click(function () {
var cancel = confirm("Are you sure? Entered data will be lost.")
if (cancel != true) {
event.preventDefault(); // cancel the event
}
});
});
//$('input:checkbox[name="Sponsor-Organization"]').on('switchChange.bootstrapSwitch', function(event, state) {
</script>

Added an ID to each dropdown and then reference it in my jQuery.
<div style="margin-bottom: 15px">
<div class="row switchOn">
<div class="editor-label">
#Html.LabelFor(model => model.MemberOrgId, "Organization")
</div>
<div class="editor-field">
#Html.DropDownList("OrganizationId", null, String.Empty, new { #class = "form-control", #id = "OrgIdDropDown" })
#Html.ValidationMessageFor(model => model.MemberOrgId)
</div>
</div>
<div class="row switchOff">
<dliv class="editor-label">
#Html.LabelFor(model => model.SponsorOrgId, "Sponsor")
</dliv>
<div class="editor-field" >
#Html.DropDownList("SponsorId", null, String.Empty, new { #class = "form-control", #id = "SponsorIdDropDown" })
#Html.ValidationMessageFor(model => model.SponsorOrgId)
</div>
</div>
</div>
jQuery:
$('input:checkbox[name="Sponsor-Organization"]').on('switchChange.bootstrapSwitch', function (event, state) {
var checked = state;
if (checked) {
$('.switchOn').removeClass('hide');
$('.switchOff').addClass('hide');
$('#SponsorIdDropDown').val("");
}
else {
$('.switchOff').removeClass('hide');
$('.switchOn').addClass('hide');
$('#OrgIdDropDown').val("");
}
});

Related

remote validation does not work for partial view

I have order with several order items and I use partial view to load order items. I want to validate OrderLineItemEntity's ProductCode but it does not work. Every other property validation works which is not in partial view. How can I force to validate partial view too?
Order View:
<div id="orderLineItemsContainer" class="form-group">
#Html.EditorFor(model => model.OrderLineItems)
</div>
OrderLineItems View:
#model SalesManagementSystem.Models.OrderEntity
#Html.EditorFor(model => model.OrderLineItems)
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
OrderLineItem View:
#model SalesManagementSystem.Models.OrderLineItemEntity
<div class="form-inline col-md-12" style="margin-bottom: 5px">
<div class="form-group col-md-6">
#Html.LabelFor(model => model.ProductCode, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.ProductCode, new { htmlAttributes = new { #class = "form-control", id = "ProductCode" } })
#Html.ValidationMessageFor(model => model.ProductCode, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group col-md-6">
#Html.LabelFor(model => model.Quantity, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { #class = "form-control", id = "ProductQuantity" } })
#Html.ValidationMessageFor(model => model.Quantity, "", new { #class = "text-danger" })
</div>
</div>
#if (Model != null)
{
<a onclick="deleteRow('#Model.ProductCode')">Delete</a>
}
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
ValidationController:
public JsonResult IsProductCodeValid(int ProductCode){...}
This is how I update my order items when new item is added. I think I need to add something here.
$("#btnAdd").click(function () {
var order = {
'Id': $("#Id").val(),
'Date': $("#Date").val(),
'ConsultantId': $("#ConsultantId").val(),
'OrderLineItems': getOrderLineItems()
};
$.ajax({
url: '#Url.Action("AddOrderItem", "Orders")',
type: "POST",
data: {
order: order
},
success: function (partialView) {
$("#orderLineItemsContainer").html(partialView);
},
failure: function (response) {
alert("failed");
}
});
});
Update:
I tried adding
jQuery.validator.unobtrusive.parse("#ProductCode");
And
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
Still not working
you can add a name and id (like ProductForm) property to your partial view form
after that, in cshtml file's script section
you can add a screen control method like this
function ScreenControl() {
if ($('#ProductForm')[0].checkValidity()) {
// do what do you want
} else {
$("#btnSave2").click();
}
}
and you should add 2 buttons to bottom of the form, one of them should be hidden like
<label class="col-md-1 control-label"></label>
<div class="col-md-1">
<button class="btn btn-sm btn-primary" style="float: right" type="button" id="btnSave" name="btnSave" value="Save" onclick="ScreenControl()">
<i class="fa fa-save"></i>
Save
</button>
</div>
<button class="btn btn-sm btn-primary" type="submit" id="btnSave2" name="btnSave2" value="Save" style="display: none">
<i class="fa fa-save"></i> Save
</button>

Refresh DIV using partial view in MVC5

I am trying to refresh a div based on the dropdown selection. I have a main view which uses a partial view (_Module). The main view has a dropdown; upon selecting the dropdown I am trying to change the content in the partial view which in turn would be reflected on the main view.
The main view:
#model Test.Models.CreateDirectoryModel
#{
ViewBag.Title = "CreateAdmin";
}
#using (Html.BeginForm("CreateAdmin", "RDBWeb", FormMethod.Post))
{
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#ProductType").change(function () {
var catType = $(this).val();
$("#result").load('#(Url.Action("GetPPOFlag", "RDBWeb", null, Request.Url.Scheme))?catType=' + catType);
});
});
</script>
#Html.ValidationSummary(true)
<div class="form-horizontal">
<h4>Create a New Directory</h4>
<hr />
<div class="form-group">
#Html.LabelFor(model => model.DirectoryNumber, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DirectoryNumber)
#Html.ValidationMessageFor(model => model.DirectoryNumber)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProductType, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.ProductType, new SelectList(Model.ProductType), "Select Product")
#Html.ValidationMessageFor(model => model.ProductType)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DirectoryName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DirectoryName)
#Html.ValidationMessageFor(model => model.DirectoryName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AdminName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.AdminName, ViewBag.Drop as SelectList, "Select Admin")
#Html.ValidationMessageFor(model => model.AdminName)
</div>
</div>
<div id="result">
#if(Model.Module != null)
{
{Html.RenderPartial("_Module", Model.Module);}
}
</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>
</div>
}
The partial view is:
#model Test.Models.CreateDirectoryModel
#foreach (string s in Model.Module)
{
#Html.LabelFor(a => s.ToString());
}
The methods relevant for these in the controller are:
public ActionResult GetPPOFlag(string catType)
{
ProdTypeModel p1 = new ProdTypeModel();
int flag = p1.GetPPOFlag(catType);
return RedirectToAction("GetModule", new { flag = flag });
}
[HttpGet]
public ActionResult GetModule(int flag)
{
ModuleType m1 = new ModuleType();
List<string> moduleList= m1.GetModules(flag);
return PartialView("_Module", moduleList);
}
My problem is that by default the Partial view object is null initially as the dropdown value is yet to be chosen. I added a check to render the partial view only if the object is not null; but that does not load the new values into the partial view. All I see is that the GetModule method is invoked and the partial view method is called as well, but there is no change in the div on the main page nor the partial view.
try to do like this, just keep an empty div inside in the main view like this
<div id="result">
</div>
On dropdown selection change, give a ajax call and get partial view and render html in the div
$('#result').empty();
$("#result").html(data);

ASP MVC jquery validation in bootsrap tabs causes an undesired postback

I have a form with 3 bootstrap tabs in it. Client Validation works correctly when the tab where the validation error occurs is open and submit button is clicked. However, when i switch to a tab with no errors (while having errors in other tabs) a post back occurs and i get the correct validation messages.
Its a minor issue, but post back is not desired in this situation, because full client side validation must be completed before sending request to the server.
How can i correct this behavior?
Below is a copy of my form HTML:
#model RBZPOSMVC.ViewModel.CreateEditItem
....
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<ul class="nav nav-tabs">
<li class="active"><a data-toggle="tab" href="#Details">Item Details</a></li>
<li><a data-toggle="tab" href="#Sales">Sale Price Groups</a></li>
<li><a data-toggle="tab" href="#Purchases">Purchase Price Groups</a></li>
</ul>
<div class="tab-content">
<div id="Details" class="tab-pane fade in active">
<div class="form-group">
#Html.LabelFor(model => model.Item.ItemCode, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Item.ItemCode, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Item.ItemCode, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Item.ItemName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Item.ItemName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Item.ItemName, "", new { #class = "text-danger" })
</div>
</div>
.... // more form controls
</div>
<div class="hidden">
#for (var i = 0; i < Model.PriceGroupList.Count; i++)
{
<div class="form-group" id="#Model.PriceGroupList[i].PriceGroupTypeId">
#Html.HiddenFor(model => model.PriceGroupList[i].PriceGroupId)
#Html.LabelFor(model => model.PriceGroupList[i].PriceGroupName,
Model.PriceGroupList[i].PriceGroupName,
htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PriceGroupList[i].Price, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PriceGroupList[i].Price, "", new { #class = "text-danger" })
</div>
</div>
}
</div>
<div id="Sales" class="tab-pane fade in ">
</div>
<div id="Purchases" class="tab-pane fade in ">
</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 {
<script>
$.validator.setDefaults({
ignore: ""
});
</script>
#Scripts.Render("~/bundles/items")
#Scripts.Render("~/bundles/jqueryval")
}
Since two of you tabs are hidden when you submit the form, you need to configure the $.validator to validate hidden elements (which are not validated by default).
You current use of $.validator.setDefaults({ ignore: "" }); is not correct for jquery version 2.2.0 (I believe that usage was depreciated in version 1.9) and it needs to be
$.validator.setDefaults({
ignore: []
});
Note: do not add the above inside $(document).ready()

Submit Button on Razor View doesn't call Action Result - MVC

I have an issue with my submit button not calling the actionresult. I have set the breakpoint in the action result itself so i know that the actionResult is not even being called. Thank you in advance for your guidance.
View:
#model CCQAS.WebApp.Areas.Credentialing.Models.TransferCustodyViewModel
#using CCQAS.API.Model.Enums
#{var PersonId = ViewBag.SessionPersonId;}
#{ViewBag.Title = "Transfer Custody ";
ViewBag.HelpText = "When this record transfer becomes effective, responsibility for updating and maintaining this credentials record will be transferred to the gaining UIC";}
#using (Html.BeginForm("CreateCustodyTransfer", "TransferCustody", FormMethod.Post, new { #id = "transfer-custody-form", #role = "form" }))
{
#Html.AntiForgeryToken()
<div class="row">
<div class="col-md-12">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">
Transfer Custody for #Html.DisplayFor(model => model.LastNameCommaFirstName)
#Html.Partial("_SectionHelp", (string)ViewBag.HelpText)
</h3>
</div>
<div class="panel-body">
<div class="row">
<div class="col-sm-4 col-md-4">
<div class="form-group require">
#Html.LabelFor(model => model.UIC, "Transfer Record To")
<div class="input-group focus" tabindex="0" id="uic_txt">
#Html.EditorFor(model => model.UIC, "Uic", new { serviceLevel = true })
</div>
#Html.ValidationMessageFor(model => model.UIC)
</div>
</div>
<div class="col-sm-4 col-md-4">
<div class="form-group require">
#Html.LabelFor(model => model.ReasonId)
#Html.EnumDropDownListFor(model => model.ReasonId, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ReasonId)
</div>
</div>
<div class="col-sm-4 col-md-4">
<div class="form-group require" hidden="hidden" id="divOtherReason">
#Html.LabelFor(model => model.OtherReasonTxt)
#Html.TextBoxFor(model => model.OtherReasonTxt, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.OtherReasonTxt)
</div>
</div>
</div>
<div class="row">
<div class="col-sm-4 col-md-4">
<div class="form-group require">
#Html.LabelFor(model => model.EffectiveDateString)
#Html.TextBoxFor(model => model.EffectiveDateString, new { #class = "form-control", #disabled = "disabled" })
#Html.ValidationMessageFor(model => model.EffectiveDate)
</div>
</div>
</div>
</div>
<div class="panel-footer text-center">
<input type="submit" value="Submit" data-loading-text="Submitting..." class="btn btn-primary" autocomplete="off" id="submitButton" />
<button type="button" onclick="goBack()" class="btn btn-default">Cancel</button>
</div>
</div>
</div>
</div>
}
#section scripts{
<script>
$(function () {
var uic = $("#UIC");
var reasonId = $("#ReasonId");
var otherReason = $("#OtherReasonTxt");
$('#submitButton').click(function (event) {
if ((uic.val() != "" && reasonId.val() != "" && reasonId.val() != 99999) || (uic.val() != "" && reasonId.val() != "" && otherReason.val() != "")) {
if (!confirm("Are you sure you want to transfer custody?")) {
resetButtonState();
return false;
}
}
});
});
function goBack() {
window.location.href = document.referrer;
}
$('#ReasonId').change(function () {
toggleOtherReason();
});
//Other Reason fields will only display if "Other" is selected from the ReasonId drop down list
function toggleOtherReason() {
var reasonId = $("#ReasonId").val();
if (reasonId == 99999) {
$("#divOtherReason").show();
}
else {
$("#divOtherReason").hide();
}
}
</script>
}
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateCustodyTransfer(TransferCustodyViewModel viewModel)
{
string serviceCode = null;
var result = mtfService.GetMtfId(viewModel.UIC, serviceCode, null);
viewModel.MTFId = (long)result;
var model = new CredCustody();
{
model.UIC = viewModel.UIC;
model.ReasonId = viewModel.ReasonId;
model.OtherReasonTxt = viewModel.OtherReasonTxt;
model.UserMtfId = CurrentUser.PrimaryMtfId;
model.UserText = CurrentUser.Name;
model.CredProviderId = this.CredProvider.CredProviderId;
model.AuditUserId = CurrentUser.UserId;
model.MTFId = viewModel.MTFId;
};
long credCustodyId = this.credCustodyService.CreateCredCustody(model);
SetPageMessage(PageMessageType.Success, String.Format("Custody Transferred"));
return RedirectToAction("SearchResults", "ProviderSearch");
}

Passing Model in ViewModel to controller get null (Edit Form)

This edit form was already success, then i want to add add comment to this form, to do this i'm following this article
http://www.arrangeactassert.com/when-to-use-html-renderpartial-and-html-renderaction-in-asp-net-mvc-razor-views/
i create the viewmodel named CaseInternalEditViewModel
public class CaseInternalEditViewModel
{
public CaseInternalEditViewModel()
{
caseComment = new List<CaseComment>();
}
public String caseIDComment { get; set; }
public CaseInternal caseInternal { get; set; }
public List<CaseComment> caseComment { get; set; }
}
and change model in View :
#model myCHMTest.Models.CaseInternalEditViewModel
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Edit</h2>
<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>
<div class="container">
<fieldset>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<legend>CaseInternal</legend>
<div class="container">
#Html.HiddenFor(model => model.caseIDComment)
#Html.HiddenFor(model => model.caseInternal.ID)
#Html.HiddenFor(model => model.caseInternal.CaseID)
#Html.HiddenFor(model => model.caseInternal.StatusID)
#* #Html.HiddenFor(model => model.caseInternal.CreatedNIK)*#
#Html.HiddenFor(model => model.caseInternal.CreatedBy)
#Html.HiddenFor(model => model.caseInternal.CreatedDt)
#Html.HiddenFor(model => model.caseInternal.SLA)
#Html.HiddenFor(model => model.caseInternal.SLAFlag)
#Html.HiddenFor(model => model.caseInternal.DatCreated)
#Html.HiddenFor(model => model.caseInternal.DayResolved)
#Html.HiddenFor(model => model.caseInternal.CategoryID)
<div class="sixteen columns">
<div class="fbbluebox">
<div class="editor-label">
#Html.LabelFor(model => model.caseInternal.CaseID)
#Html.DisplayFor(model => model.caseInternal.CaseID)
#Html.ValidationMessageFor(model => model.caseInternal.CaseID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.caseInternal.Title)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.caseInternal.Title)
#Html.ValidationMessageFor(model => model.caseInternal.Title)
</div>
</div>
<hr />
</div>
<div class="one-third column">
<div class="editor-label">
#Html.LabelFor(model => model.caseInternal.BranchID)
</div>
<div class="editor-field">
#Html.DropDownList("BranchID")
#Html.ValidationMessageFor(model => model.caseInternal.BranchID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.caseInternal.ProjectID, "InternalProject")
</div>
<div class="editor-field">
#Html.DropDownList("ProjectID", null, new { #onchange = "javascript:cascadingdropdown();" })
#Html.ValidationMessageFor(model => model.caseInternal.ProjectID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.caseInternal.SubProjectID, "InternalSubProject")
</div>
<div class="editor-field">
#Html.DropDownList("SubProjectID", String.Empty)
#*#Html.DropDownListFor(model => model.SubProjectID, new SelectList(Enumerable.Empty<SelectListItem>()))*#
#Html.ValidationMessageFor(model => model.caseInternal.SubProjectID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.caseInternal.PengaduanID, "InternalPPengaduan")
</div>
<div class="editor-field">
#Html.DropDownList("PengaduanID", String.Empty)
#Html.ValidationMessageFor(model => model.caseInternal.PengaduanID)
</div>
</div>
<div class="one-third column">
<div class="editor-label">
#Html.LabelFor(model => model.caseInternal.CreatedNIK)
</div>
<div class="editor-field">
#* #Html.TextBoxFor(model => model.caseInternal.CreatedNIK, new { disabled = "disabled" })
#Html.ValidationMessageFor(model => model.caseInternal.CreatedNIK)*#
<input type="text" name="InitialNIK" value="#Model.caseInternal.CreatedNIK" disabled="disabled"/>
</div>
<div class="editor-label">
#Html.LabelFor(model => model.caseInternal.CreatedBy)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.caseInternal.CreatedBy, new { disabled = "disabled" })
#Html.ValidationMessageFor(model => model.caseInternal.CreatedBy)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.caseInternal.CreatedDt)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.caseInternal.CreatedDt, new { disabled = "disabled" })
#Html.ValidationMessageFor(model => model.caseInternal.CreatedDt)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.caseInternal.AssignGroupID)
</div>
<div class="editor-field">
#Html.DropDownList("AssignGroupID", null, new { #onchange = "javascript:memberdropdown();" })
#Html.ValidationMessageFor(model => model.caseInternal.AssignGroupID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.caseInternal.AssignMemberID)
</div>
<div class="editor-field">
#Html.DropDownList("AssignMemberID", String.Empty)
#Html.ValidationMessageFor(model => model.caseInternal.AssignMemberID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.caseInternal.StatusID)
</div>
<div class="editor-field">
#Html.DropDownList("StatusID",null, new { #disabled = "disabled" })
#Html.ValidationMessageFor(model => model.caseInternal.StatusID)
</div>
</div>
<div class="one-third column">
<div class="editor-label">
#Html.LabelFor(model => model.caseInternal.SLA)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.caseInternal.SLA, new { disabled = "disabled" })
#Html.ValidationMessageFor(model => model.caseInternal.SLA)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.caseInternal.SLAFlag)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.caseInternal.SLAFlag, new { disabled = "disabled" })
#Html.ValidationMessageFor(model => model.caseInternal.SLAFlag)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.caseInternal.DayResolved)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.caseInternal.DayResolved, new { disabled = "disabled" })
#Html.ValidationMessageFor(model => model.caseInternal.DayResolved)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.caseInternal.DatCreated)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.caseInternal.DatCreated, new { disabled = "disabled" })
#Html.ValidationMessageFor(model => model.caseInternal.DatCreated)
</div>
</div>
<div class="sixteen columns">
<div class="fbgreybox" >
<div class="editor-label">
#Html.LabelFor(model => model.caseInternal.Description)
</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.caseInternal.Description, new { style = "width: 100%; height: 100px;" })
#Html.ValidationMessageFor(model => model.caseInternal.Description)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.caseInternal.LinkCase)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.caseInternal.LinkCase)
#Html.ValidationMessageFor(model => model.caseInternal.LinkCase)
</div>
</div>
<p>
<input type="submit" value="Save" class="uibutton large confirm"/>
#Html.ActionLink("Back to List", "Index", "CaseInternal", new { #class = "uibutton" })
</p>
</div>
</div>
}
</fieldset>
</div>
#using (Ajax.BeginForm("Comment", "CaseInternal", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "myGrid", OnSuccess = "done" }))
{
#*<input type="text" id="caseEka" name="caseEka" />*#
#Html.HiddenFor(model => model.caseIDComment)
<input type="text" id="Comment" name="Comment"/>
}
<div id="myGrid">
#Html.Partial("_showComment", Model.caseComment)
</div>
<script type="text/javascript">
function done() {
document.getElementById('Comment').value = '';
}
function cascadingdropdown() {
var idDept = $("#ProjectID").val();
var subProject = $('#SubProjectID').val();
var urlemp = '#Url.Action("GetSubProjectFromProjectID")';
var select = $('#SubProjectID');
$.ajax({
type: "POST",
url: urlemp,
data: { id: idDept },
error: function (jqXHR, textStatus, errorThrown) {
alert("error" + jqXHR.responseText);
},
success: function (returndata) {
if (returndata.ok) {
select.empty();
$.each(returndata.data, function (index, itemData) {
if (subProject == itemData.ID) {
select.append($('<option selected="selected"></option>').val(itemData.ID).html(itemData.SubProjectName));
} else {
select.append($('<option></option>').val(itemData.ID).html(itemData.SubProjectName));
}
});
select.show('slow');
// $("#ProjectID").attr("disabled", "disabled");
}
else {
window.alert(' error : ' + returndata.message);
}
}
}
);
}
function getNameNik() {
window.alert("AAAASSDSD");
var idDept = $("#CreatedNIK").val();
var urlemp = '#Url.Action("GetNameNik")';
$.ajax({
type: "POST",
url: urlemp,
data: { id: idDept },
error: function (jqXHR, textStatus, errorThrown) {
alert("error" + jqXHR.responseText);
},
success: function (returndata) {
if (returndata.ok) {
$('#nikLabel').text("");
$.each(returndata.data, function (index, itemData) {
$('#nikLabel').text(itemData.FirstName + " " + itemData.LastName);
});
}
else {
window.alert(' error : ' + returndata.message);
}
}
}
);
}
function memberdropdown() {
var idDept = $("#AssignGroupID").val();
var subProject = $('#AssignMemberID').val();
var urlemp = '#Url.Action("GetMemberFromGroupID")';
var select = $('#AssignMemberID');
$.ajax({
type: "POST",
url: urlemp,
data: { id: idDept },
error: function (jqXHR, textStatus, errorThrown) {
alert("error" + jqXHR.responseText);
},
success: function (returndata) {
select.empty();
if (returndata.ok) {
$.each(returndata.data, function (index, itemData) {
if (subProject == itemData.ID) {
select.append($('<option selected="selected"></option>').val(itemData.ID).html(itemData.UserName));
} else {
select.append($('<option></option>').val(itemData.ID).html(itemData.UserName));
}
});
select.show('slow');
// $("#ProjectID").attr("disabled", "disabled");
}
else {
window.alert(' error : ' + returndata.message);
}
}
}
);
}
function start() {
cascadingdropdown();
memberdropdown();
}
window.onload = start;
// window.onload = memberdropdown;
</script>
and here my controller:
public ActionResult Edit(string id)
{
CaseInternal caseinternal = db.CaseInternals.Find(id);
caseinternal.NullSafeTrimStrings();
ViewBag.PengaduanID = new SelectList(db.InternalPPengaduans, "ID", "PPengaduanName", caseinternal.PengaduanID);
ViewBag.ProjectID = new SelectList(db.InternalProjects, "ID", "ProjectName", caseinternal.ProjectID);
ViewBag.SubProjectID = new SelectList(db.InternalSubProjects, "ID", "SubProjectName", caseinternal.SubProjectID);
ViewBag.CategoryID = new SelectList(db.MasterCategories, "ID", "CategoryName", caseinternal.CategoryID);
ViewBag.AssignGroupID = new SelectList(db.MasterGroups, "ID", "GroupName", caseinternal.AssignGroupID);
ViewBag.AssignMemberID = new SelectList(db.MasterAssignUsers, "ID", "UserName", caseinternal.AssignMemberID);
ViewBag.BranchID = new SelectList(branchObject.A2BR, "BRCODE", "BRNAME", caseinternal.BranchID);
ViewBag.StatusID = new SelectList(db.MasterStatus, "ID", "StatusName", caseinternal.StatusID);
CaseInternalEditViewModel caseInternalEdit = new CaseInternalEditViewModel();
caseInternalEdit.caseInternal = caseinternal;
caseInternalEdit.caseIDComment = caseinternal.CaseID;
var commentCase = db.CaseComments.Where(p => p.CaseID == caseinternal.CaseID).OrderByDescending(p => p.CreatedDt);
foreach (CaseComment cas in commentCase)
{
caseInternalEdit.caseComment.Add(cas);
}
return View(caseInternalEdit);
}
[HttpPost]
public ActionResult Edit(CaseInternalEditViewModel caseinternalEdit)
{
//CaseInternalEditViewModel caseinternalEdit
CaseInternal caseinternal = caseinternalEdit.caseInternal;
if (ModelState.IsValid)
{
db.Entry(caseinternal).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.PengaduanID = new SelectList(db.InternalPPengaduans, "ID", "PPengaduanName", caseinternal.PengaduanID);
ViewBag.ProjectID = new SelectList(db.InternalProjects, "ID", "ProjectName", caseinternal.ProjectID);
ViewBag.SubProjectID = new SelectList(db.InternalSubProjects, "ID", "SubProjectName", caseinternal.SubProjectID);
ViewBag.CategoryID = new SelectList(db.MasterCategories, "ID", "CategoryName", caseinternal.CategoryID);
ViewBag.AssignGroupID = new SelectList(db.MasterGroups, "ID", "GroupName", caseinternal.AssignGroupID);
ViewBag.AssignMemberID = new SelectList(db.MasterAssignUsers, "ID", "UserName", caseinternal.AssignMemberID);
ViewBag.BranchID = new SelectList(branchObject.A2BR, "BRCODE", "BRNAME", caseinternal.BranchID);
ViewBag.StatusID = new SelectList(db.MasterStatus, "ID", "StatusName", caseinternal.StatusID);
return View(caseinternalEdit);
}
the modelstate is always invalid, because some field is null, field2 in dropdownlist is null when passing to controller.
is the viewbag the problem? should i change the name of viewbag?
#Html.EditorFor(model => model.caseInternal.Title)
is rendered to
<input class="text-box single-line" id="caseInternal_Title" name="caseInternal.Title" type="text" value="ViewModel" />
but dropdownlist
<select id="BranchID" name="BranchID"><option selected="selected" value="001">KANTOR PUSAT NON OPERASIONAL </option>
the different is the name, the branch should be caseinternal.branchID maybe it will work, but how to do that?
You have:
#Html.DropDownList("BranchID")
You want:
#Html.DropDownListFor(model => model.caseInternal.BranchID)
OR if you really don't want to use a DropDownListFor() for whatever reason....
#Html.DropDownList("caseInternal_BranchID")

Resources