My Bootstap modal form is covering the entire screen - asp.net-core

I have a modal form in my ASP.NET Core 3.1 project. The problem is my modal form unexpectedly is covering entire of screen and I don't know why.
My _Modal.cshtml:
#model MyProject.CommonLayer.PublicClass.BootstrapModel
<div aria-hidden="true" aria-labelledby="#Model.AreaLabeledId" role="dialog" tabindex="-1" id="#Model.ID" class="modal fade">
<div class="modal-dialog #Model.ModalSizeClass">
<div class="modal-content" style="border-radius:6px;">
</div>
</div>
</div>
My modal.js file:
(function ($) {
function Modal() {
var $this = this;
function initilizeModel() {
$("#modal-action").on('loaded.bs.modal', function (e) {
}).on('hidden.bs.modal', function (e) {
$(this).removeData('bs.modal');
});
}
$this.init = function () {
initilizeModel();
}
}
$(function () {
var self = new Modal();
self.init();
})
}(jQuery))
and my BooststrapModal.cs file:
public class BootstrapModel
{
public string ID { get; set; }
public string AreaLabeledId { get; set; }
public ModalSize Size { get; set; }
public string Message { get; set; }
public string ModalSizeClass
{
get
{
switch (this.Size)
{
case ModalSize.Small:
return "modal-sm";
case ModalSize.Large:
return "modal-lg";
case ModalSize.Medium:
default:
return "";
}
}
}
public enum ModalSize
{
Small,
Large,
Medium
}
}
In the end of my index.cs file, for modal I put:
#Html.Partial("_Modal", new BootstrapModel { ID = "modal-action", Size = BootstrapModel.ModalSize.Medium })
#section AdminScripts {
<script src="~/js/modal/modal.js"></script>
}
Finally when button is clicked, the modal form covers my entire screen.
Please help. Thanks in advance.

Related

how to get data from database using ajax asp.net core

According to the following codes i have created the Get Handler in Index Model
public IActionResult OnGetCustomer(CustomerSearchModel searchModel)
{
CustomerCombine combine = new CustomerCombine
{
MyViewModels = _customerApplication.GetAll(searchModel)
};
return Partial("./Customer", combine);
}
and this is my Razor View:
#model CustomerCombine
<form asp-page="./Index" asp-page-handler="Customer"
method="get"
data-ajax="true"
data-callback=""
data-action="Refresh"
>
<div class="form-group">
<input asp-for="#Model.MySearchModel.FullName" class="form-control " placeholder="search..." />
</div>
<button class="customer-submit btn btn-success" type="submit">جستجو</button>
</form>
<table>
#foreach (var item in #Model.MyViewModels)
{
<tr>
<td>#item.Id</td>
<td>#item.FullName</td>
<td>#item.Mobile</td>
<td>#item.Email</td>
<td>#item.Address</td>
<td>#item.Image</td>
</tr>
}
</table>
My modal is displayed successfully,and i can see my database's data, but when i fill search field and click on search button , nothing happens
can any one help me plz?:)
and this is my jquey codes: i dont anything about Jquery and these codes were ready and now i dont knoe how i should use from it
$(document).on("submit",
'form[data-ajax="true"]',
function (e) {
e.preventDefault();
var form = $(this);
const method = form.attr("method").toLocaleLowerCase();
const url = form.attr("action");
var action = form.attr("data-action");
if (method === "get") {
const data = form.serializeArray();
$.get(url,
data,
function (data) {
CallBackHandler(data, action, form);
});
} else {
var formData = new FormData(this);
$.ajax({
url: url,
type: "post",
data: formData,
enctype: "multipart/form-data",
dataType: "json",
processData: false,
contentType: false,
success: function (data) {
CallBackHandler(data, action, form);
},
error: function (data) {
alert("خطایی رخ داده است. لطفا با مدیر سیستم تماس بگیرید.");
}
});
}
return false;
});
});
function CallBackHandler(data, action, form) {
switch (action) {
case "Message":
alert(data.Message);
break;
case "Refresh":
if (data.isSucceced) {
window.location.reload();
} else {
alert(data.message);
}
break;
case "RefereshList":
{
hideModal();
const refereshUrl = form.attr("data-refereshurl");
const refereshDiv = form.attr("data-refereshdiv");
get(refereshUrl, refereshDiv);
}
break;
case "setValue":
{
const element = form.data("element");
$(`#${element}`).html(data);
}
break;
default:
}
}
function get(url, refereshDiv) {
const searchModel = window.location.search;
$.get(url,
searchModel,
function (result) {
$("#" + refereshDiv).html(result);
});
}
1.The third parameter of $.get() is the success function.
2.There is no isSucceced property in your postback data. The postback data is the partial view html code. You need use $("xxx").html(data); to update the partial view code.
3.Model Binding binds the property by name, <input asp-for="#Model.MySearchModel.FullName"/> does not match the CustomerSearchModel searchModel.
public IActionResult OnGetCustomer(CustomerSearchModel MySearchModel)
Whole working demo and more details I have commented on the code pls check carefully:
Model
public class CustomerCombine
{
public List<MyViewModel> MyViewModels { get; set; }
public CustomerSearchModel MySearchModel { get; set; }
}
public class CustomerSearchModel
{
public string FullName { get; set; }
}
public class MyViewModel
{
public int Id { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
public string Address { get; set; }
public string Image { get; set; }
}
View(Index.cshtml)
#page
#model IndexModel
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
#Html.Partial("Customer",Model.CustomerCombine)
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
#section Scripts
{
<script>
$(document).on("submit",'form[data-ajax="true"]',function (e) {
e.preventDefault();
var form = $(this);
const method = form.attr("method").toLocaleLowerCase();
const url = form.attr("action");
var action = form.attr("data-action");
if (method === "get") {
const data = form.serializeArray();
$.get(url,data,function (data) {
console.log(data); //you can check the response data in Console panel
CallBackHandler(data, action, form);
});
} else {
var formData = new FormData(this);
$.ajax({
url: url,
type: "post",
data: formData,
enctype: "multipart/form-data",
dataType: "json",
processData: false,
contentType: false,
success: function (data) {
CallBackHandler(data, action, form);
},
error: function (data) {
alert("خطایی رخ داده است. لطفا با مدیر سیستم تماس بگیرید.");
}
});
}
return false;
});
//}); //remove this.......
function CallBackHandler(data, action, form) {
switch (action) {
case "Message":
alert(data.Message);
break;
case "Refresh":
$(".modal-body").html(data); //modify here....
break;
case "RefereshList":
{
hideModal();
const refereshUrl = form.attr("data-refereshurl");
const refereshDiv = form.attr("data-refereshdiv");
get(refereshUrl, refereshDiv);
}
break;
case "setValue":
{
const element = form.data("element");
$(`#${element}`).html(data);
}
break;
default:
}
}
function get(url, refereshDiv) {
const searchModel = window.location.search;
$.get(url,
searchModel,
function (result) {
$("#" + refereshDiv).html(result);
});
}
</script>
}
Partial View does not change anything
#model CustomerCombine
<form asp-page="./Index" asp-page-handler="Customer"
method="get"
data-ajax="true"
data-callback=""
data-action="Refresh"
>
<div class="form-group">
<input asp-for="#Model.MySearchModel.FullName" class="form-control " placeholder="search..." />
</div>
<button class="customer-submit btn btn-success" type="submit">جستجو</button>
</form>
<table>
#foreach (var item in #Model.MyViewModels)
{
<tr>
<td>#item.Id</td>
<td>#item.FullName</td>
<td>#item.Mobile</td>
<td>#item.Email</td>
<td>#item.Address</td>
<td>#item.Image</td>
</tr>
}
</table>
PageModel
public IActionResult OnGetCustomer(CustomerSearchModel MySearchModel)//change here....
{
CustomerCombine combine = new CustomerCombine
{
MyViewModels = _customerApplication.GetAll(searchModel) //be sure here contains value...
};
return Partial("./Customer", combine);
}
Result:

dropzone image passing with a model

I have a form that includes several inputs(text) and below them, there is a dropzone area. I need to pass these data and image together in a model.
I have a model like this:
public BannerItem bannerItem { get; set; }
public IFormFile imagefile { get; set; }
I am using tags like asp-for and i dont know how to bind dropzone image to the imagefile. I tried js but it didn't work. Can you help me with this?
Here is a whole working demo you could follow:
Model
public class TestVM
{
public BannerItem bannerItem { get; set; }
public IFormFile imagefile { get; set; }
}
public class BannerItem
{
public int Id { get; set; }
public string Name { get; set; }
}
View (Index.cshtml)
#model TestVM
<form asp-action="Test" asp-controller="Home" method="post" enctype="multipart/form-data" class="dropzone dz-clickable form-horizontal form-bordered" id="dropzoneForm">
<div class="form-group form-actions">
<input asp-for="bannerItem.Name" />
<div class="col-md-9 col-md-offset-4">
<button type="submit" id="submit" class="btn btn-sm btn-primary"><i class="fa fa-floppy-o"></i> Upload</button>
</div>
</div>
</form>
#section Scripts
{
<link rel="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/dropzone.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/dropzone.js"> </script>
<script>
function myParamName() {
return "imagefile";
}
Dropzone.options.dropzoneForm = {
autoProcessQueue: false,
paramName: myParamName, // The name that will be used to transfer the file
uploadMultiple: true,
parallelUploads: 100,
init: function () {
console.log("active");
var wrapperThis = this;
$("#submit").click(function (e) {
e.preventDefault();
wrapperThis.processQueue();
});
},
accept: function (file, done) {
done();
}
};
</script>
}
Controller
public class HomeController : Controller
{
public async Task<IActionResult> Index()
{
return View();
}
[HttpPost]
public async Task<ActionResult> Test(TestVM model)
{
//do your sufff...
}
}

How to dynamically add an item to a list within a list in a ViewModel using Razor and .NET Core 2.2?

I've been following this tutorial (i did it in asp.net core 2.2):
http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/ on how to edit a variable lenght list in asp.net. In this tutorial, we're just handling a list of gifts. I'm trying to apply this method to a more complex model.
I have an object called Workout.cs who contains a List of Section.cs. The Section.cs object contains a List of Movement.cs
public class Workout
{
public string Name { get; set; }
public IEnumerable<Section> Sections { get; set; } = new List<Section>();
}
public class Section
{
public int NbRounds { get; set; }
public string Name { get; set; }
public IEnumerable<Movement> Movements { get; set; } = new List<Movement>();
}
public class Movement
{
public string Name { get; set; }
}
WorkoutController
public IActionResult BlankSection()
{
return PartialView("_SectionEditor", new Section());
}
public IActionResult BlankMovement()
{
return PartialView("_MovementEditor", new Movement());
}
Index.cshtml
#model Workout
<h2>Workout</h2>
<form asp-action="Index" method="post" asp-controller="Workout">
<div id="editorRows">
#foreach (var item in Model.Sections)
{
<partial name="_SectionEditor" model="item" />
}
</div>
<a id="addItem" asp-action="BlankSection" asp-controller="Workout">Add Section...</a> <br />
<input type="submit" value="Finished" />
</form>
#section scripts {
<script>
$("#addItem").click(function () {
$.ajax({
url: this.href,
cache: false,
success: function (html) { $("#editorRows").append(html); }
});
return false;
});
</script>
}
_SectionEditor.cshtml
#model Section
#{
Layout = "~/Views/Shared/_LayoutEditor.cshtml";
}
<div class="editorRow">
#using (Html.BeginCollectionItem("sections"))
{
<span>Name: </span> #Html.EditorFor(m => m.Name);
<span>Rounds: </span>#Html.EditorFor(m => m.NbRounds, new { size = 4 });
}
delete
<div id="editorMovement">
#foreach (var item in Model.Movements)
{
<partial name="_MovementEditor" model="item" />
}
</div>
<a id="addMovement" asp-action="BlankMovement" asp-controller="Workout">Add Movement...</a> <br />
</div>
#section Scripts {
<script>
$(document).ready(function () {
$("a.deleteRow").on("click", function () {
$(this).parents("div.editorRow:first").remove();
return false;
});
});
$("#addMovement").click(function () {
$.ajax({
url: this.href,
cache: false,
success: function (html) { $("#editorMovement").append(html); }
});
return false;
});
</script>
}
MovementEditor.cshtml
#model Movement
#{
Layout = "~/Views/Shared/_LayoutEditor.cshtml";
}
<div class="editorMovement">
#using (Html.BeginCollectionItem("movements"))
{
<span>Name: </span> #Html.TextBoxFor(m => m.Name);
}
delete
</div>
#section Scripts {
<script>
$(document).ready(function () {
$("a.deleteMovement").on("click", function () {
$(this).parents("div.editorMovement:first").remove();
return false;
});
});
</script>
}
With the tutorial, it's working fine when I'm adding sections to my workout, but when I'm trying the same to add movements to my sections, it's not working anymore. I would like to be able to add as many sections as I want to my workout, and for each section, as many movements as I want, and send it to the controller. How could I do that ?
thanks a lot
First: MovementEditor appears to be a partial in the controller, but not in the view file (despite the '_').
Second: since _SectionEditor is a partial view, you can't define #section scripts in it, because it's already defined in the main view Index. To solve this issue, you need to put all the scripts in the main view Index.
P.S: don't forget to change jquery selectors for items in the partial views, i.e: $("#addMovement") will not point to the anchor tag because it was not there when the DOM tree was created. Instead write $("body #addMovement") and it will get the anchor tag.

Update kendo grid columns without page reload in ASP MVC

I have a kendo grid where user can select list of columns from grid and save the selection by giving name (i.e view name). Each saved selection (view name) will show up as drop-down above grid so that user can change grid columns whenever they want. In current implementation, whenever user selects view name from one drop-down value to other, i call action method to select that view name as current view name. Then page reloads to invoke Index' action method to retrieve current view names columns values. I am using visible attribute in grid to show and hide columns in grid.
Now i was wondering if i can update the grid columns without reloading the page when user change the view name from the dropdown.
Thanks
Sanjeev
Screenshot:
Here is my setup:
ViewModel:
namespace MvcApplicatioin.Models
{
public class EmployeeViewModel
{
public EmployeeColumns EmployeeColumns { get; set; }
public IEnumerable<SelectListItem> EmployeeViewNames { get; set; }
public long EmployeeSelectedViewId { get; set; }
}
public class EmployeeResponse
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class EmployeeColumns
{
public bool Id { get; set; }
public bool FirstName { get; set; }
public bool LastName { get; set; }
}
}
Controller:
public class EmployeeController : Controller
{
// GET: Employee
public ActionResult Index()
{
var service = new EmployeeService();
EmployeeViewModel model = new EmployeeViewModel();
long currentViewId;
//setup views and column preferences
EmployeeColumns employeeColumns = service.GetCurrentEmployeeColumnsPreferences();
model.EmployeeColumns = employeeColumns;
model.EmployeeViewNames = service.GetAllEmployeeViewNames(out currentViewId);
model.EmployeeSelectedViewId = currentViewId;
return View(model);
}
}
Razor:
#using Kendo.Mvc.UI
#{
ViewBag.Title = "Employee Info:";
}
<h3 style="margin-bottom: 10px;">Employee Info</h3>
<input id="btnSearch" type="button" value="Search" class="btn_Search" />
<div class="row">
<div class="col-sm-12">
#(Html.Kendo().Grid<MvcApplicatioin.Models.EmployeeResponse>()
.Name("GridEmployee")
.Columns(columns =>
{
columns.Bound(e => e.Id).Width("170px").Visible(Model.EmployeeColumns.Id);
columns.Bound(e => e.FirstName).Width("190px").Visible(Model.EmployeeColumns.FirstName);
columns.Bound(e => e.LastName).Width("170px").Visible(Model.EmployeeColumns.LastName);
})
.ToolBar(tools =>
{
tools.Template(#<text>
<div class="col-lg-4 col-md-5 col-sm-5 col-xs-7 pull-right" style="padding-right: 0;">
<div class="form-group" style="margin-bottom: 0;">
#Html.Label("Grid View:", new { #class = "col-sm-3 col-xs-4 control-label view" })
<div class="col-sm-7 col-xs-6" style="padding-left: 0;">
#Html.DropDownList("lstEmployeeViewNames", new SelectList(Model.EmployeeViewNames, "Value", "Text", Model.EmployeeSelectedViewId), "- Select View Name -", new { #class = "form-control", #style = "height: auto;" })
</div>
</div>
</div>
</text>);
})
.Pageable(x => x.PageSizes(new int[] { 10, 20, 50, 100 }).ButtonCount(4))
.AutoBind(false)
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(10)
.ServerOperation(false)
.Read(read => read.Action("SearchEmployee", "Employee")))
)
</div>
</div><!--//row-->
<script type="text/javascript">
$('#btnSearch').click(function (e) {
e.preventDefault(); //This prevent the submit button onclick from submitting by itself
$('#GridEmployee').data('kendoGrid').dataSource.read();
});
//Change event for Dropdown placed inside the Grid's Toolbar - To Change the view
$("#lstEmployeeViewNames").change(function (e) {
var selectedViewId = $('select#lstEmployeeViewNames option:selected').val();
if (selectedViewId == null || selectedViewId == '') {
alert("Please select the view name from the dropdown first !!");
return;
}
$.post("/Employee/SetEmployeeColumnsCurrentPreferences", { viewId: selectedViewId }, function (data) {
window.top.location.reload();
});
});
</script>
This is how I would do a search in client. I know it doesn't tell how to show and hide columns, but at least it could put you on the right track.
The trick is to manipulate $("#GridEmployee") instead of posting.
function search() {
var searchCriteria = $("#searchField").val();
var gridData = $("#GridEmployee").data("kendoGrid");
if searchCriteria != "") {
gridData.dataSource.filter({ field: "FirstName", operator: "contains", value: searchCriteria });
} else {
gridData.dataSource.filter({});
}
}

Hot Towel SPA Modal Dialog knockout bindings and validation

I'm building a SPA using the Hot Towel SPA template.
Here's my problem:
I have a view where I put the information related to a Venue (Name, Description, Address, etc.)
Associated with the Venue there are different Rooms with their own fields (Name, Description, Type, etc.)
I have a list of Rooms and a button "Add New Room".When I hit the button, a modal dialog pops up, I fill the form with the requested information then I save. After the dialog is closed the list gets updated.
I am able to retrieve the information from the dialog, but I'm not able to trigger the validation rules if the fields are left blank. Also the datacontext.HasChanges() returns always true.
Is it possible to use the modal dialog like any other view?
Here's part of the code I am using:
From Model.cs:
public class Venue
{
[Key]
public int VenueId { get; set; }
[Required(ErrorMessage = "Venue Name is required.")]
[Display(Name = "Venue Name")]
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<Room> Fields { get; set; }
...
}
public class Room
{
[Key]
public int RoomId { get; set; }
[Required(ErrorMessage = "Name is required.")]
[Display(Name = "Name")]
public string Name { get; set; }
public string Description { get; set; }
public string Notes { get; set; }
public int VenueId { get; set; }
public virtual Venue Venue { get; set; }
...
}
From venuedetail.js:
define(['services/datacontext',
'services/model',
'durandal/plugins/router',
'durandal/system',
'durandal/app',
'services/logger',
'viewmodels/roommodal'],
function (datacontext, model, router, system, app, logger, roommodal) {
...
var addRoom = function () {
var newRoom= datacontext.manager.createEntity("Room");
roommodal.room = newRoom;
app.showModal(roommodal).then(function (response) {
if (response) {
}
return true;
});
};
...
From roommodal.js:
define(['durandal/app', 'services/datacontext', 'durandal/system', 'durandal/plugins/router', 'services/logger'],
function (app, datacontext, system, router, logger) {
var isSaving = ko.observable(false);
var room= ko.observable();
activate = function(routeData) {
return true;
};
hasChanges = ko.computed(function() {
return datacontext.hasChanges(); // Always true ?
});
canSave = ko.computed(function() {
return hasChanges() && !isSaving();
});
canDeactivate = function () {
return true;
};
var save = function(dialogResult) {
this.modal.close(dialogResult);
};
var cancel = function() {
this.modal.close(false);
};
var vm = {
activate: activate,
save: save,
canSave: canSave,
cancel: cancel,
canDeactivate: canDeactivate,
room: room,
hasChanges: hasChanges,
title: 'Add room'
};
return vm;
From roommodal.html:
<div class="messageBox">
<div class="modal-header">
<h3 data-bind="text: title"></h3>
<i class="icon-asterisk" data-bind="visible: hasChanges"></i>
</div>
<div class="modal-body">
<div data-bind="with: room">
<label for="name">Name</label>
<input id="name" data-bind="value: name, valueUpdate: 'afterkeydown'"
placeholder="Enter name" />
<div>
<label>Description</label>
<textarea data-bind="value: description"
placeholder="Enter description"></textarea>
</div>
<div>
<label>Notes</label>
<textarea data-bind="value: notes"
placeholder="Enter notes"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-info"
data-bind="click: cancel, enable: canSave">
<i class="icon-undo"></i>Cancel</button>
<button class="btn btn-info"
data-bind="click: save, enable: canSave">
<i class="icon-save"></i>Save</button>
</div>
Any help will be greatly appreciated.
Thanks in advance.
Validation is triggered when you try to save using datacontext.saveChanges() which you don't do in this piece of code, instead, you are just closing the modal window.
Easiest way to see if saving was successful is to check HasChanges afterwards - it should be false if everything went well, otherwise it will be true.
datacontext.HasChanges() returns true when you enter modal window because you create an entity and place it in your context before opening the modal window. You can only ignore HasChanges and silently CancelChanges before closing the modal window.