Block Editor for CheckBox MVC with Javascript - javascript

You have a button that calls to a Modal window...
Agregar Producto <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
this is the javascript that executes it
<script type="text/javascript">
$(document).ready(function () {
$('#agregarproducto').click(function (e) {
e.preventDefault();
var $link = $(this);
var title = $link.text();
$('#AgregarProducto.modal-title').html(title);
var url = $(this).attr('href');
$.get(url, function (data) {
$('#AgregarProducto .te').html(data);
$('#AgregarProducto').modal();
$('#editorfocus').focus() // set focus
});
});
});
</script>
and the partial view looks like this ...
It is looking to put the EditorFor "disabled" and the checkbox unchecked (false) when the modal is executed, and in the case that the user checks the checkbox to unblock the text box in question ... it also seeks to validate that when they press the "submit" button of the form, validate that the checkbox is marked or unmarked .... in case it is marked, a value will be verified in the ... otherwise it will send the message
"You must enter a quantity or uncheck the box"
I have the following modal view "AgregarProducto.cshtml"...
<h2>Agregar Producto</h2>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script type="text/javascript" src="~/Scripts/jquery-ui-1.12.1.js"></script>
<script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
</head>
<body>
<div class="form-group">
<div class="col-md-10">
<label>Agregar Cantidad</label>
<input type="checkbox" name="checkcantidad" id="idcheckcantidad" value="false" />
#Html.EditorFor(model => model.d_Cantidad, new { htmlAttributes = new { #class = "form-control", id = "editorprecio" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Kn_CodigoProducto, "Producto", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Kn_CodigoProducto, new { htmlAttributes = new { #class = "form-control", #autofocus = "true" , id = "editorfocus" } })
<div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button class="btn btn-success" id="mybtn" type="submit">
Agregar Producto
<i class="glyphicon glyphicon-ok"></i>
</button>
</div>
</div>
</div>
}
</body>
</html>
and I have the following script in the main view...
<script type="text/javascript">
$(function () {
var st = $("#idcheckcantidad").attr('checked');
$("#idcheckproveedor").change(function () {
st = this.checked;
if (st) {
$("#txtSearch").prop("disabled", false);
}
else {
$("#txtSearch").prop("disabled", true);
}
});
$("#mybtn").click(function () {
if (st && ($("#txtSearch").val() == "" || $("#txtSearch").val() == null)) {
alert("Debe Ingresar una cantidad o desmarcar la casilla");
return false;
}
});
});
</script>
My code does not do anything ... when opening the modal, only the focus defined in the button that opens the modal is executed, but I am not able to block the EditorFor from the modal view and obviously my validation does not work, I am setting the code correctly? , what's going on? any help for me?
PS: when changing the script to my modal window "AddProduct.cshtml" nothing happens either

you can use begin form and keep your form content in it and on submit call the javascript function to validate it. if validation is successfull then return true from that method otherwise prevent form submit
#using (Html.BeginForm("method", "controller", FormMethod.Post, new { enctype = "multipart/form-data", onsubmit = "validateForm(event)" }))
{
// HTML form COntent goes here
}
javascript code for validation
<script>
function validateForm(event)
{
//default is validation fail
var isValid = false;
// validation rules goes here - update isValid value to true if pass else fail
// your code here
// check whether form valid
if(!isValid) {
//if validation fails then prevent submit
event.preventDefault();
}
return isValid;
}

Related

Disabling Button After First Click Ajax.BeginForm with Javascript

Having an issue hiding/disabling the submit button with it also submitting the form. I have tried adding: onclick="this.value='Submitting, Please Wait.'; this.disabled='disabled';" into the input submit field which will disable the button but wont submit the form. I have tried placing this into the javascript portion also and it not working. I have tried things like this also:
$("#SignInButton").one('click', function (event) {
event.preventDefault();
$(this).prop('disabled', true);
});
I am at a loss because a lot of examples I am looking at are for html.beginform and this old form was set up with Ajax.BeginForm. Any insight on how to either just hide the button or disable the button with the code below would be much help!!
<div id="LoginModal" style="display:none;padding:1rem;max-width:580px;">
#using (Ajax.BeginForm("Login", "Accounts",
new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "OnSuccess",
OnFailure = "OnSuccess"
}))
{
<div>
Other Form Data
<div>
#Html.Hidden("ItemID", Model.ItemID)
<input type="submit" id="SignInButton" data-loading-text="Signing in" class="button success" value="Sign In" />
</div>
</div>
}
<script type="text/javascript">
var ready;
ready = function () {
$(".fancybox").fancybox({
'content': $('#LoginModal'),
'onStart': function () { $("#LoginModal").css("display", "block"); },
'onClosed': function () { $("#LoginModal").css("display", "none"); }
});
};
$(document).ready(ready);
$(document).on('page:load', ready);
</script>
EDIT!!!!!
<div id="LoginModal" style="display:none;padding:1rem;max-width:580px;">
#using (Ajax.BeginForm("Login", "Accounts", new AjaxOptions { HttpMethod = "POST", OnSuccess = "OnSuccess", OnFailure = "OnSuccess" }))
{
<h1>Sign In</h1>
var displayLocalLogin = "";
#Html.AntiForgeryToken()
#Html.ValidationSummary(false, "", new { #class = "text-error" })
#Html.Sitecore().FormHandler()
<div class="">
<div class="row">
<div class="internal">
<div class="medium-12 columns">
</div>
<div class="medium-12 border-top columns">
<div class="form-group">
<label for="UserName">UserName <span class="required">*</span></label>
#Html.TextBoxFor(m => m.UserName)
#Html.ValidationMessageFor(m => m.UserName)
</div>
</div>
<div class="medium-12 columns">
<div class="form-group">
<label for="Password">Password <span class="required">*</span></label>
#Html.PasswordFor(m => m.Password)
#Html.ValidationMessageFor(m => m.Password)
</div>
</div>
<div class="medium-12 columns" style="padding-bottom: 10px;">
<div class="form-group">
</div>
</div>
<div class="medium-5 columns left">
<div class="form-group">
<div>
<div>
#Html.Hidden("ItemID", Model.ItemID)
<input type="submit" id="SignInButton" data-loading-text="Signing in" class="button success" value="Sign In">
</div>
</div>
</div>
</div>
</div>
#if (string.Equals(System.Configuration.ConfigurationManager.AppSettings["EnableSalesForceLogin"], "true", StringComparison.InvariantCultureIgnoreCase))
{
displayLocalLogin = "displaynone";
#Html.Partial("/salesforceloginpartial.cshtml")
}
</div>
</div>
}
<script type="text/javascript">
$("#SignInButton").one('click', function (event) {
$(this).prop('disabled', 'disabled');
});
//function OnSuccess(data) {
// alert(data);
// $('#LoginModal').parent.html(data).css("display", "block");
// $("#LoginModal").css("display", "block");
//}
var ready;
ready = function () {
$(".fancybox").fancybox({
'content': $('#LoginModal'),
'onStart': function () { $("#LoginModal").css("display", "block"); },
'onClosed': function () { $("#LoginModal").css("display", "none"); }
});
};
$(document).ready(ready);
$(document).on('page:load', ready);
</script>
You can disable the button in the next event loop excecution by using setTimeout(func, 0):
$("#SignInButton").one('click', function (event) {
setTimeout(function() {
event.preventDefault();
$(this).prop('disabled', true);
}, 0);
});
This will block the button right after the user click, but it will pass the first click.
I think you should set the attribute disabled to "disabled" instead
$(this).prop('disabled', 'disabled');
You can probably try to make use of ajaxStart and ajaxStop methods from jquery.
http://api.jquery.com/ajaxStart/
http://api.jquery.com/ajaxStop/
May be something like, in ajaxStart disable the button.
You need to submit the form after disabling button.
Give to your form an id:
#using (Ajax.BeginForm("Login",
"Accounts",
new AjaxOptions { HttpMethod = "POST", OnSuccess = "OnSuccess", OnFailure = "OnSuccess" },
new { id = "formId"}))
and then submit it by javascript:
$("#SignInButton").one('click', function (event) {
event.preventDefault();
$(this).prop('disabled', true); //disable button
$("#formId").submit(); //submit the form
});

Disable button once its being clicked on after Ajax - ASP.NET MVC5

I have a form in ASP.NET MVC5 that uses FormMethod.Post I have a Create button that submits the form, but how would I get it to work so that if you click Create then it disables the button. I have tried:
onclick="this.disabled = true"
But then the form is not submitted, hower when it is removed it allows you to add multiple records when clicking Create
This is my code for the form:
#section scripts {
#Scripts.Render("~/bundles/jqueryajaxval")
#Scripts.Render("~/bundles/jqueryval")
<script language="javascript" type="text/javascript">
// cancel
$(document).on("click",
"#CancelForm",
function(e) {
var uri = '#Html.Raw(Url.Action("Index", "Membership"))';
window.location = uri;
e.preventDefault();
});
// submit
$(document).on("click", "#submitMembership", function(e) {
// Perform Ajax request to check if CAE/IPI Number is unique.
var caeipinumber = $('#addMembershipCAEIPINumber').val();
if (caeipinumber) {
$.ajax({
url: '#Url.Action("IsCAEIPINumberUnique", "Membership")',
data: ({ 'caeipinumber': caeipinumber, 'personaIdToIgnore': null }),
type: 'POST',
async: false,
cache: false,
success: function(result) {
if (result.toLowerCase() == "false") {
// Number is not unique and already exists, so display validation error to the user.
e.preventDefault();
$('#addMembershipForm').validate().showErrors({ 'CAEIPINumber': 'CAE / IPI Number already exists!' });
return false;
}
return true;
},
error: function(xhr, status, error) {
}
});
}
});
</script>
}
#section additionalStyles {
}
#section modal {
}
<article class="row">
<h1 class="pageTitle artistHeader fw200 mb20 mt10">#ViewBag.Title</h1>
<div class="col-md-1"></div>
<div id="createMembership" class="col-md-10 formContainer">
<div class="panel">
<div class="panel-heading">
<span class="panel-title">
<i class="glyphicon glyphicon-pencil"></i> Details of New Membership
</span>
</div>
#using (Html.BeginForm("AddMembership", "Membership", FormMethod.Post, new { id = "addMembershipForm", role = "form", #class = "theme-primary form-horizontal" }))
{
<fieldset>
<legend style="display: none">Add Membership Form</legend>
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="panel-body p25 fill bt0 pbn">
<div class="form-group">
#Html.LabelFor(x => x.MembershipName, new { #class = "control-label col-md-3" })
<div class="col-md-8">
#Html.TextBoxFor(x => x.MembershipName, new { id = "addMembershipName", #class = "form-control", placeholder = "Enter Membership Name..." })
#Html.ValidationMessageFor(x => x.MembershipName, string.Empty, new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(x => x.CAEIPINumber, new { #class = "control-label col-md-3" })
<div class="col-md-8">
#Html.TextBoxFor(x => x.CAEIPINumber, new { id = "addMembershipCAEIPINumber", #class = "form-control", placeholder = "Enter CAE / IPI Number..." })
#Html.ValidationMessageFor(x => x.CAEIPINumber, string.Empty, new { #class = "text-danger" })
</div>
</div>
</div>
<div class="panel-footer">
<div class="text-center">
<input type="button" class="btn btn-primary" id="CancelForm" value="Cancel" />
<input id="submitMembership" type="submit" class="btn btn-primary" value="Create" />
</div>
</div>
</fieldset>
}
</div>
</div>
<div class="col-md-1"></div>
</article>
You should listen the form submit event, the submit input used trigger the form submit event and when the event is triggered you can disable the Button you clicked.
$("#form1").submit(function (){
$("#submitbtn").prop ("disabled",true);
$.ajax({requestprops,success:function(){
$("#submitbtn").prop ("disabled",false);
}});
});
This should work:
<script>
function setDisable(id) {
document.getElementById(id).disabled=true;
};
</script>
<input id="submitMembership" type="submit" onclick="setDisable(this.id)" class="btn btn-primary" value="Create" />
First, I would remove the binding on the click of the submit button and instead bind on the submit event.
Replace your submit button function with the following:
$("#addMembershipForm").submit(function (e) {
var submitButton = $(this).find(':input[type=submit]').prop('disabled', true); // Find and disable the submit button
// Perform Ajax request to check if CAE/IPI Number is unique.
var caeipinumber = $('#addMembershipCAEIPINumber').val();
if (caeipinumber) {
$.ajax({
url: '#Url.Action("IsCAEIPINumberUnique", "Membership")',
data: ({ 'caeipinumber': caeipinumber, 'personaIdToIgnore': null }),
type: 'POST',
async: false,
cache: false,
success: function(result) {
if (result.toLowerCase() == "false") {
// Number is not unique and already exists, so display validation error to the user.
submitButton.prop('disabled', false); // Enable submit button
e.preventDefault(); // Do not submit form
$('#addMembershipForm').validate().showErrors({ 'CAEIPINumber': 'CAE / IPI Number already exists!' });
}
},
error: function(xhr, status, error) {
}
});
}
});
var submitButton = $(this).find(':input[type=submit]').prop('disabled', true);is used to find and then disable the button.
It will then do your unique check the same as you had in your original question. However, we will enable the submit button if it returns false so the user can re-submit.

How to insert record with ajax in modal Twitter Bootstrap

You want to add a product to a list through a modal window twitter bootstrap, in the window you are asked to add the name and the quantity.
my button that calls the modal:
<a data-toggle="modal" data-target="#myDesayuno" href="#" class="btn btn-primary">Desayunos <span class="glyphicon glyphicon-plus-sign"></span> </a> #:
my modal and its call script:
<!-- Modal -->
<div class="modal fade" id="myDesayuno" #*tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"*#>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 class="modal-title">Agregar Desayuno</h3>
</div>
<div class="modal-body">
<div class="form-horizontal">
<form id="myForm" method="post">
<div class="form-group">
#Html.LabelFor(model => model.Kn_CodigoProducto, "Desayuno", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Kn_CodigoProducto", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Kn_CodigoProducto, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.d_Cantidad, "Cantidad", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.d_Cantidad, new { #class = "form-control", placeholder = "Agregar Cantidad" })
#Html.ValidationMessageFor(model => model.d_Cantidad, "", new { #class = "text-danger" })
</div>
</div>
</form>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<input type="reset" id="btnSubmit" class="btn btn-primary" data-dismiss="modal" value="Agregar Desayuno" />
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script>
function launch_modal(id) {
// Hide all modals using class if required.
$('.modal').modal('hide');
$('#'+id).modal('show');
}
</script>
}
It is wanted that when the user enters name and quantity of product, this click in "Add Product" and the products are loaded in the list, as it shows the following figure:
But I'm not getting the expected result, but add the product to my list ... it is necessary to refresh the page to view it through user interface.
the modal form button has an id = "btnSubmit" that calls the following script:
<script type="text/javascript">
$(document).ready(function () {
$("#btnSubmit").click(function () {
var myformdata = $("#myForm").serialize();
$.ajax({
type: "POST",
url: "/Ordens/AgregarDesayuno",
data: myformdata,
success: function () {
$("#myDesayuno").modal("hide");
}
})
})
})
</script>
and my ActionResult in mi controller:
[HttpPost]
public ActionResult AgregarDesayuno(AddProducto addproducto)
{
if (ModelState.IsValid)
{
var cantidad = addproducto.d_Cantidad;
var ordentmp = db.OrdenDetalleTmps.Where(o => o.UserName == User.Identity.Name && o.Kn_CodigoProducto == addproducto.Kn_CodigoProducto).FirstOrDefault();
if (ordentmp == null)
{
var buscaproducto = db.Productoes.Find(addproducto.Kn_CodigoProducto);
var temporal = new OrdenDetalleTmp
{
v_Nombre = buscaproducto.v_Nombre,
Precio_Unitario = Convert.ToInt16(buscaproducto.Precio_Unitario),
d_Cantidad = Convert.ToInt16(addproducto.d_Cantidad),
UserName = User.Identity.Name,
Kn_CodigoProducto = buscaproducto.Kn_CodigoProducto,
};
db.OrdenDetalleTmps.Add(temporal);
db.SaveChanges();
return RedirectToAction("Create");
}
}
ViewBag.Kn_CodigoProducto = new SelectList(ComboHelper.GetDesayuno(), "Kn_CodigoProducto", "v_Nombre");
return PartialView(addproducto);
}
my GET method from the main view (open the list):
[HttpGet]
public ActionResult Create()
{
var view = new NewOrdenView()
{
f_Ingreso = DateTime.Now,
ListaOrdenDetallesTmps = db.OrdenDetalleTmps.Where(edt => edt.UserName == User.Identity.Name).ToList(),
};
ViewBag.Kn_CodigoProducto = new SelectList(ComboHelper.GetDesayuno(), "Kn_CodigoProducto", "v_Nombre");
return View(view);
}
How can I add a product to my list so that the user does not need to refresh the page to visualize it? I have very little knowledge of modal windows, any help for me?
coordinating greetings
Try loading page from ajax success..it will load latest records in your list
try this one. hope this helps
<script type="text/javascript">
$(document).ready(function () {
$("#btnSubmit").click(function () {
var myformdata = $("#myForm").serialize();
$.ajax({
type: "POST",
url: "/Ordens/AgregarDesayuno",
data: myformdata,
success: function () {
window.location.reload(true);
$("#myDesayuno").modal("hide");
}
})
})
})
</script>

Fill textbox on my page from the text box in my modal

In my page i have a textbox and a dropdown list, when i select my item number 10 it shows me a modal, in this modal i have a textbox and i'd like to take the information entered by the user and put it in my page texbox when i submit it in the modal.
But can't figure how to do get this information to my textbox on page.
If someone could help, would be nice :) here is my script.
$(function () {
$("#Dropdown1").change(function () {
//Recupere la value de la liste
selection = $(this).val();
//Mettre la valeur du choix de liste.
if (selection == 10) {
//Affiche le modal
$('#myModal').modal('show');
}
});
})
;
My view (some things have been deleted) :
<h4 class="mb"><i class="fa fa-angle-right"></i> Example</h4>
<div class="form-horizontal style-form">
<div class="form-group">
#Html.LabelFor(m => m.X.Y, new { #class = "col-sm-d col-sm-2 control-label" })
<div class="col-sm-2">
#Html.TextBoxFor(m => m.X.Y, new { #class = "form-control" })
</div>
<div class="col-sm-2">
#Html.EnumDropDownListFor(m => m.X.Y, new { #class = "form-control", #id = "Dropdown1" })
</div>
And i'd like to fill the #Html.textboxfor with wha's inside my modal.
I made this so :
$('#myModal').on('hidden.bs.modal', function () {
$('#X_Y').val($('#Y_X'));
})
but still getting [object Object] in my field instead of what's inside the modal.

How to disable/hide a Partial View based on IList values?

I want to disable or hide a PartialView based on values inside two different ILists. Both of these lists are stored in two Session variables, _UserRoleList and _PartialRoleList.
The list contents of _UserRoleList are of type User which contains the following properties:
UserName
RoleID
RoleDescription
SID
The list contents of _PartialRoleList are of type PartialRole which contains the following properties:
PartialName
RoleID
AccessLevelID
AccessLevelDescription
Case 1 - Disable all input controls inside the Partial View:
Disable ALL input controls (textboxes, listboxes, checkboxes, dropdownlists) on the specified PartialView (with an id of "frmClientDetails") if a RoleID of 3 is found in both session lists.
Case 2 - Set all input controls to read-only inside the Partial View:
All input controls (textboxes, listboxes, checkboxes, dropdownlists) on the specified PartialView (with an id of "frmClientDetails") should have their read-only attribute set to true if aRoleID of 2 is found in both session lists.
Question:
Would it be better to retrieve the two lists and then use a jQuery .each to loop through and search for equality on the RoleID fields? Would another option be to use Razor? If pseudo code could be provided, that would be a great help.
Controller snippet:
public ViewResult Index() /* Master View, starting point of application */
{
int userID;
IList<User> userRoleList;
IList<PartialRole> partialRoleList;
WindowsIdentity identity = null;
identity = WindowsIdentity.GetCurrent();
userRoleList = _homeService.GetUserDetails(identity.User.ToString());
userID = userRoleList.First().ID;
partialRoleList = _homeService.GetPartialDetails(userID);
if (Session["_UserRoleList"] == null)
{
HttpContext.Session.Contents.Add("_UserRoleList", userRoleList);
}
if (Session["_PartialRoleList"] == null)
{
HttpContext.Session.Contents.Add("_PartialRoleList", partialRoleList);
}
return View();
}
Original View - ClientDetails.cshtml:
#using InvoiceManagement.Models
#model InvoiceClient
#{
InvoiceCreditNoteViewModel viewModel = new InvoiceCreditNoteViewModel();
viewModel.Client = Model;
ViewBag.Title = "Client Details";
List<User> userRoleList = Session["_UserRoleList"] != null ? (List<User>)Session["_UserRoleList"] : null;
List<PartialRole> partialRoleList = Session["_PartialRoleList"] != null ? (List<PartialRole>)Session["_PartialRoleList"] : null;
}
#section scripts{
<script type="text/javascript">
$(document).ready(function () {
$('input[type=radio][name=optionInvoiceCreditNote]').change(function () {
if (this.value == 'invoice') {
$("#InvoiceGrid").show();
$("#CreditNoteGrid").hide();
}
else if (this.value == 'creditNote') {
$("#InvoiceGrid").hide();
$("#CreditNoteGrid").show();
}
});
$('#showActive').click(function (e) {
if($(this).prop('checked') === true){
var url = '#Url.Action("FilterActiveOnlyAgreements")';
$.get(url, { invoiceClientID: '#Model.ID' }, function (result) {
$('#agreementGrid').html(result);
});
}
else {
var url = '#Url.Action("FilterAllAgreements")';
$.get(url, { invoiceClientID: '#Model.ID' }, function (result) {
$('#agreementGrid').html(result);
});
}
});
});
</script>
}
#Html.Partial("ClientDetailsFormPartial", viewModel.Client)
#if (viewModel.Client.ID > 0)
{
#Html.Partial("ClientDetailsAgreementPartial")
#Html.Partial("InvoiceCreditNoteContainerPartial", viewModel)
}
Partial View - ClientDetailsFormPartial:
#using InvoiceManagement.Models
#model InvoiceClient
#using (#Html.BeginForm("ClientDetails", "Client", FormMethod.Post, new { #id = "frmClientDetails" }))
{
<div class="container-fluid">
<div class="row">
<div class="col-xs-2">
<h2>Client Details</h2>
</div>
<div class="col-xs-2" style="min-height: 70px;">
Search New Client
</div>
<div class="form-group col-xs-2" style="min-height: 70px;">
<div class="input-group" style="top: 21px">
<span class="input-group-addon" id="client-ID">Client ID</span>
#Html.TextBox("ID", Model.ID, new { #class = "form-control", #readonly = "readonly" })
</div>
<div class="has-error">
#Html.ValidationMessageFor(m => m.ID, String.Empty, new { #class = "help-block" })
</div>
</div>
<div class="form-group col-xs-3" style="min-height: 70px;">
<div class="input-group" style="top: 21px">
<span class="input-group-addon" id="accounting-ID">Accounting ID</span>
#if (Model.AID == null && Model.ID == 0)
{
#Html.TextBoxFor(m => m.AID, new { #class = "form-control" }) }
else
{
#Html.TextBoxFor(m => m.AID, new { #class = "form-control", #readonly = "readonly" }) }
</div>
</div>
<div style="padding-top: 22px;">
<div class="has-error">
#Html.ValidationMessageFor(m => m.AID, String.Empty, new { #class = "help-block" })
</div>
</div>
</div>
<div class="row">
<div class="form-group col-xs-7">
<div class="input-group">
<span class="input-group-addon" id="client-name">Client Name</span>
#Html.TextBoxFor(m => m.InvoiceClientName, new { #class = "form-control", #name = "InvoiceClientName" })
</div>
<div class="has-error">
#Html.ValidationMessageFor(m => m.InvoiceClientName, String.Empty, new { #class = "help-block" })
</div>
</div>
</div>
<div class="row">
<div class="form-group col-xs-3">
<div class="input-group">
<span class="input-group-addon" id="default-tax-code-1">Default Tax Code 1</span>
#Html.DropDownListFor(m => m.DefaultTaxCodeID1, (IEnumerable<SelectListItem>)ViewBag.PopulateDefaultTaxCode1, new { #class = "form-control", #id = "default-tax-code1-ID", #name = "defaultTaxCodeID1" })
</div>
</div>
<div class="form-group col-xs-3 col-xs-offset-1">
<div class="input-group">
<span class="input-group-addon" id="default-tax-code-2">Default Tax Code 2</span>
#Html.DropDownListFor(m => m.DefaultTaxCodeID2, (IEnumerable<SelectListItem>)ViewBag.PopulateDefaultTaxCode2, new { #class = "form-control", #id = "default-tax-code2-ID", #name = "defaultTaxCodeID2" })
</div>
</div>
</div>
<div class="row">
<div class="form-group col-xs-3">
<div class="input-group">
<span class="input-group-addon" id="status">Status</span>
#Html.DropDownListFor(m => m.StatusID, (IEnumerable<SelectListItem>)ViewBag.PopulateStatus, new { #class = "form-control", #id = "status-ID", #name = "statusID" })
</div>
</div>
</div>
<div class="row">
<div class="col-xs-2 col-xs-offset-7">
#if (Model == null || Model.ID == 0)
{
<button type="submit" class="btn btn-default">Add New Client</button>
}
else
{
<button type="submit" class="btn btn-default">Update Existing Client</button>
}
</div>
</div>
</div>
}
Since disabled controls will not post back, its pointless to generate all that extra html, and since readonly controls cannot be edited, again it seems pointless to generate all that extra html and then send it all back unchanged to the server when you submit your form.
A better approach, performance wise would be to have 2 partial views (say) _ClientDetails.cshtml and _ReadOnlyClientDetails.cshtml. The first would contain your form and its editable controls and submit button, and the second would contain only the text values of your properties, for example
#Html.DisplayNameFor(m => m.InvoiceClientName)
#Html.DisplayFor(m => m.InvoiceClientName)
Then in your controller method that generates you main view, set a view model property (or ViewBag property) to indicate which partial to display, for example
ViewBag.IsReadonly = true; // or omit depending on your logic
and in the main view
#if(ViewBag.IsReadonly)
{
#Html.Partial("_ReadOnlyClientDetails", viewModel.Client)
}
else
{
#Html.Partial("_ClientDetails", viewModel.Client)
}
Side note: Everything between you first #{ ... } except ViewBag.Title = "Client Details"; belongs in the controller method, not the view. And to do something like viewModel.Client = Model; makes no sense at all. Your view should be #model InvoiceCreditNoteViewModel and since you're not passing a model to the view, then viewModel.Client = Model; would not make sense anyway since its always null.
Its also not clear why your using Session. The code in your controller should be something like
IList<User> userRoleList = _homeService.GetUserDetails(identity.User.ToString());
int userID = userRoleList.First().ID;
IList<PartialRole> partialRoleList = _homeService.GetPartialDetails(userID)
List<int> values = new List<int>(){ 2, 3 };
if (userRoleList.Any(x => values.Contains(x.RoleID)) && partialRoleList.Any(x => values.Contains(x.RoleID)))
{
ViewBag.IsReadonly = true;
}

Categories