disable textboxfor using a checkboxfor razor mvc and jquery - razor

I am trying to disable/enable an #Html.TextBoxFor in razor using an #Html.CheckBoxFor
I have defined my CheckBoxFor in this manner:
#Html.CheckBoxFor(m => m.ResYearChecked, new { Name = "ResYearChecked", id = "ResYearChecked" })
#Html.TextBoxFor(m => m.SearchResYear, new { Name = "SearchResYear", id = "SearchResYear" })
and I am trying to call the script:
<script>
$('ResYearChecked').change(function () {
$("SearchResYear").prop("disabled", !$(this).is(':checked'));
});
</script>
Do I need to add the onclick attribute to the CheckBoxFor?

I was able to figure out the solution. I enabled the attribute readonly for the #Html.TextBoxFor. I then removed the readonly attribute once the #Html.CheckBoxFor was checked.
Here is the code for my #Html.CheckBoxFor and #Html.TextBoxFor
#Html.CheckBoxFor(m => m.ResYearChecked, new { Name = "ResYearChecked", id = "ResYearChecked" })
#Html.TextBoxFor(m => m.SearchResYear, new { Name = "SearchResYear", id = "SearchResYear", #readonly = "readonly" })
Here is the JavaScript
<script>
$('#ResYearChecked').change(function () {
if ($(this).is(":checked")) {
$("#SearchResYear").removeAttr("readonly");
$("#SearchResYear").focus();
} else {
$("#SearchResYear").attr("readonly", "readonly");
}
});
</script>

Related

Passing a custom component to material ui dialog that opens it

I am trying to pass a custom component to a MUI Dialog in such way that it should open the Dialog itself and render its children.
const CustomDialog = ({children, someCustomComponent}) => {
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
return(
<>
{someCustomComponent} // use this component to call handleOpen/handleClose
<Dialog>
<DialogTitle>
<DialogTItle>
<DialogContent>{children}</DialogContent>
<DialogActions>...</DialogActions>
</Dialog>
</>
);
}
CustomDialog.propTypes = {
someCustomComponent: PropTypes.node.isRequired,
}
And then call it like this
<CustomDialog someCustomComponent={<h1>open</h1>}>
{myDialogContent}
</CustomDialog>
Is this possible? So, essentially, I don't always want a button to open my Dialog. I want to have any component I pass to it to be able to open it.
This is kind of how this is done by using Button
return(
<>
<Button onClick={handleClickOpen} />
<Dialog>
...
but I want to pass any element to it.
Thanks!
A simple way to do it is with React.cloneElement
const CustomDialog = ({ children, someCustomComponent }) => {
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
// clone the component and add the onClick handler
const customComponentClone = React.cloneElement(someCustomComponent, {
onClick: handleClickOpen
});
return (
<>
{customComponentClone}
<Dialog>
<DialogTitle>
<DialogTItle>
<DialogContent>{children}</DialogContent>
<DialogActions>...</DialogActions>
</Dialog>
</>
);
}
This way you can use it like you mentioned
<CustomDialog someCustomComponent={<h1>open</h1>}>
{myDialogContent}
</CustomDialog>
Check here a live version

How do I disable a mvc razor #Html.TextBoxFor based on what is selected in a drop down menu on the same page?

Let's say I have the following.
#Html.DropDownListFor(m => m.MyWebPage, Model.FruitsList, "Select", htmlAttributes: new { #class = "form-select detailsInfo" })
And within this drop down menu I have a selection that says "Custom" and right after that drop down I have a textbox that is autopopulated with the user's already selected option
#Html.TextBoxFor(m => m.MyWebPage, htmlAttributes: new { #class = "form-control", id="CustomFruitTextBox"})
What would I have to call in order to disable the text box if the drop down selection is not currently selected to "Custom"?
Would this require javascript or could I do this in the razor file manually?
You can try to use js to check the selected value of the dropdown:
view:
#Html.DropDownListFor(m => m.MyWebPage, Model.FruitsList, "Select", htmlAttributes: new { #class = "form-select detailsInfo" #onchange="check()" })
js:
<script>
$(function () {
check();
})
function check() {
if ($("#MyWebPage").val() != "Custom") {
$("#CustomFruitTextBox").attr("disabled", "disabled");
} else{
$("#CustomFruitTextBox").removeAttr("disabled");
}
}
</script>

how to use #htmlattributes : for datepicker

hello i'm tryinh to change simple input to date form i tried text
to show a datetime picker with DateTime property
but when i use
#Html.TextBoxFor(model => model.dateFin, new { type = "date" })
but it doesn't work
so i'm using simple input
#Html.EditorFor(model => model.dateDebut, new { htmlAttributes = new {#class = "form-control" } })
#Html.ValidationMessageFor(model => model.dateFin, "", new { #class = "text-danger" })
is there someone who's familiar with this form ?
You can create custom html helper control for datepicker like
public static class HtmlHelper
{
public static IHtmlString DatePicker(this HtmlHelper helper, string id)
{
TagBuilder input = new TagBuilder("input");
input .Attributes.Add("type", "date");
input .Attributes.Add("id", id);
return new MvcHtmlString(input.ToString());
}
}
After creating, you need to refer to this class in your razor page with #using. And you can use like #Html.DatePicker("dt1")

Kendo DateTimePicker set value from json result

I have a big trouble with pasting a value in Kendo DateTimePicker inside Kendo Grid from json result. So I have two forms on page. In first I'm loading file:
#using (Html.BeginForm("GetImportSalesModelFromFile", "ExportImport", FormMethod.Post, new { id = "GetImportSaleModelFromFileForm", enctype = "multipart/form-data" }))
{
<input id="importFileInput" type="file" accept="text/csv" name="file" class="user-success" required>
<input style="width: 100px;" type="submit" value="Add">
}
On form submit called function
$('#GetImportSaleModelFromFileForm').submit(function(e) {
e.preventDefault();
var url = $(this).attr('action');
var xhr = new XMLHttpRequest();
var fd = new FormData();
fd.append("file", document.getElementById('importFileInput').files[0]);
xhr.open("POST", url, true);
xhr.send(fd);
xhr.addEventListener("load", function(event) {
AppendImportModel(JSON.parse(event.target.response));
}, false);
});
In controller I get needed import model
public ActionResult GetImportSalesModelFromFile(HttpPostedFileBase file)
{
var importModel = _importService.ConstructSaleImportModel(file.InputStream, file.ContentType);
return Json(importModel, JsonRequestBehavior.AllowGet);
}
In function AppendImportModel I parse result and paste it in kendo grid in second form
#(Html.Kendo().Grid<ImportSaleItemModel>().Name("ImportSalesGrid")
.DataSource(dataSource => dataSource.Ajax())
.Events(x => x.DataBound("initMenus"))
.Columns(columns =>
{
columns.Bound(x => x.Goods.PictureId)
.ClientTemplate("<img style='height: 50px;' src='" + Url.Action("Contents", "FileStorage", new { id = "#= Goods.PictureId #" }) + "'/>")
.Title("")
.Sortable(false)
.HtmlAttributes(new Dictionary<string, object> { { "style", "padding: 3px !important; height: 52px !important; width:52px !important;" } });
columns.Bound(x => x.Goods.Title)
.ClientTemplate("<a onclick='ShowInfoGoodWindow(#= Goods.Id #)'>#= Goods.Title #</a><br>" +
"<span><b>#= Goods.Article #</b> <descr>#= Goods.Description #</descr></span><br><input type='hidden' name='ImportedGoodList[#= index(data)#].Id' value='#= Goods.Id #' />")
.Title("Description");
columns.Bound(x => x.Price)
.ClientTemplate("<input class='priceEditor' maxlength='10' style='width:50px; text-align: center;' type='text' name='ImportedGoodList[#= index(data)#].Price' onkeypress='return isPriceKey(event)' oninput='$(this).get(0).setCustomValidity(clearValidation);' value='#=Price.ParsedValue #'>")
.HtmlAttributes(new Dictionary<string, object> { { "style", "text-align: center;" } })
.Title("Price");
columns.Bound(x => x.Discount)
.ClientTemplate("<input class='discountEditor' maxlength='10' style='width:50px; text-align: center;' type='text' name='ImportedGoodList[#= index(data)#].Discount' onkeypress='return isPriceKey(event)' oninput='$(this).get(0).setCustomValidity(clearValidation);' value='#=Discount.ParsedValue #'>")
.HtmlAttributes(new Dictionary<string, object> { { "style", "text-align: center;" } })
.Title("Discount");
columns.Bound(x => x.DepartmentId)
.HtmlAttributes(new { #class = "templateCell" })
.ClientTemplate(Html.Kendo().DropDownList().Name("Department#=LineId#").BindTo(Model.Departments).Value("#= DepartmentId #").ToClientTemplate().ToHtmlString())
.Title("Department");
columns.Bound(x => x.SaleDateTime)
.HtmlAttributes(new { #class = "templateCell" })
.ClientTemplate(Html.Kendo().DateTimePicker().Name("SaleDateTime#=LineId#").Value("#= ConvertedSaleDateTime #").ToClientTemplate().ToHtmlString())
.Title("Sale Date");
columns.Bound(x => x.SellerId)
.HtmlAttributes(new { #class = "templateCell" })
.ClientTemplate(Html.Kendo().DropDownList().Name("Seller#=LineId#").BindTo(Model.Sellers).Value("#= SellerId #").ToClientTemplate().ToHtmlString())
.Title("Seller");
columns.Bound(x => x.IsCashPayment)
.ClientTemplate("<input type='checkbox' id='IsCashPayment#=LineId#' checked='#= IsCashPayment.ParsedValue #' class='regular-checkbox'/><label for='IsCashPayment#=LineId#'></label> Yes")
.Title("Is Cash Payment");
})
)
In all columns using "#= value #" works fine but not in this line
.ClientTemplate(Html.Kendo().DateTimePicker().Name("SaleDateTime#=LineId#").Value("#= ConvertedSaleDateTime #").ToClientTemplate().ToHtmlString())
"#= ConvertedSaleDateTime #" not changed on real value, but if I write
.ClientTemplate("#= ConvertedSaleDateTime #")
I will get right value "10/07/2013 13:15". And if I write
.ClientTemplate(Html.Kendo().DateTimePicker().Name("SaleDateTime#=LineId#").Value("10/07/2013 13:15").ToClientTemplate().ToHtmlString())
I will get Kendo DateTimePicker inside grid with value "10/07/2013 13:15"
How I can set value to this DateTimePicker from ConvertedSaleDateTime?
Please, help me. Thanks in advance.
I solved my problem via jQuery. Maybe someone needs this solution or knows something more beautiful.
In client template of SaleDateTime columnt I wrote:
columns.Bound(x => x.SaleDateTime).ClientTemplate("<input class='saleDateTimeEditor' id='SaleDateTime#=index(data)#' name='ImportedSalesList[#=index(data)#].SaleDateTime' value='#= ConvertedSaleDateTime #'>")
And in DataBound event of my kendo grid I initialized all kendo DateTimePickers:
$('.saleDateTimeEditor').each(function () {
var id = $(this).attr('id');
var value = new Date(Date.parse($(this).val()));
$("#" + id).kendoDateTimePicker({
value: value,
max: new Date(Date.now())
});
$('#'+id).attr('readonly', 'readonly');
});
ConvertedSaleDateTime is in format "yyyy/MM/dd hh:mm:ss"

How to configure Kendo Dropdownlist to work with Grid popup editor template

I've been struggling with the Kendo dropdownlist for 2 days now and just can't seem to get it configured correctly.
How do I get the Kendo Dropdownlist to show the current item of the #Model? This is my code:
#Html.TextBoxFor(model => model.ShortDescription, new { #class="wide200;" })
#(Html.Kendo().DropDownList()
.Name("importance")
.HtmlAttributes(new { style = "width: 250px" })
.DataTextField("Name")
.DataValueField("ID")
.DataSource(source => {
source.Read(read =>
{
read.Action("GetImportanceList", "Home");
})
.ServerFiltering(true);
})
.SelectedIndex(0)
)
And in my controller:
public ActionResult GetImportanceList()
{
GenericRepository<Importance> _repository = new GenericRepository<Importance>(_context);
IEnumerable<ImportanceViewModel> list = _repository.Get().ConvertToViewModelList();
return Json(list, JsonRequestBehavior.AllowGet);
}
Problem is with SelectedIndex(0) which is set to the first item. How can I set it to whatever is in the model? It's very simple to do for the textbox (first line in the code): model => model.ShortDescription. But how does this work for the dropdownlist?
I don't just want to set it upon the showing of the editor, but also want the grid to know what the new selection is after I click the Update button.
Note that this is in a custom template for the grid popup editor.
Try this,
You have to pass DropDownListId in model and ListItems.
#(Html.Kendo().DropDownListFor(m=>m.DropDownListId)
.Name("importance")
.HtmlAttributes(new { style = "width: 250px" })
.DataTextField("Name")
.DataValueField("ID")
.DataSource(source => {
source.Read(read =>
{
read.Action("GetImportanceList", "Home");
})
.ServerFiltering(true);
})
.SelectedIndex(0)
)
I asked this question to Telerik. Apparently the Name mustn't be assigned.