I am trying to fire a method in JQuery, but it won't work.
#using (Html.BeginForm("AddOrUpdateMethod", "Controller", FormMethod.Post))
{
//some code
<div class="row">
<div class="period-list">
<span class="advance-season">
<span class="glyphicon glyphicon-warning-sign margin-right10"></span>Something
</span>
#for (int i = 0; i < Model.Periods.Count; i++)
{
<div class="form-group period">
#Html.HiddenFor(model => model.Periods[i].Id, new { #Value = Model.Periods[i].Id })
<div class="pull-left inline-block col-xs-5 col-sm-5 col-md-5 col-lg-5">
<div class="text-box-with-icon calendar margin-bottom10">
#Html.TextBoxFor(model => model.Periods[i].From, "{0:dd/MM/yyyy}", new { #class = "form-control period-from", #onchange = "periodChange();" })
<span class="icon"></span>
</div>
</div>
<div class="pull-left inline-block col-xs-5 col-sm-5 col-md-5 col-lg-5">
<div class="text-box-with-icon calendar margin-bottom10">
#Html.TextBoxFor(model => model.Periods[i].To, "{0:dd/MM/yyyy}", new { #class = "form-control period-to" })
<span class="icon"></span>
</div>
</div>
}
//some code
</div>
</div>
}
And my jQuery:
<script type="text/javascript">
function periodChanged() {
$('.period-from .period-to').change(function () {
alert("click");
//some code
});
}
As you can see I tried already adding #change to textBox control. Nothing is happening. Maybe I should mention as well, that i I am using validation on model.Periods.From and model.Periods.To. Moreover this view is a partial view.
EDIT:
I changed into:
<script type="text/javascript">
$(document).ready( function () {
$('.period-from .period-to').click(function () {
alert("click");
if (Model.Periods.All(p=>p.To.Day - p.From.Day + 1 <= 7)) {
}
});
});
but it still doesn't work.
Try this way
$(document).on('change','.period-from .period-to') {
alert("click");
//some code
});
#using (Html.BeginForm("AddOrUpdateMethod", "Controller", FormMethod.Post))
{
//some code
<div class="row">
<div class="period-list">
<span class="advance-season">
<span class="glyphicon glyphicon-warning-sign margin-right10"></span>Something
</span>
#for (int i = 0; i < Model.Periods.Count; i++)
{
<div class="form-group period">
#Html.HiddenFor(model => model.Periods[i].Id, new { #Value = Model.Periods[i].Id })
<div class="pull-left inline-block col-xs-5 col-sm-5 col-md-5 col-lg-5">
<div class="text-box-with-icon calendar margin-bottom10">
#Html.TextBoxFor(model => model.Periods[i].From, "{0:dd/MM/yyyy}", new { #class = "form-control period-from", #onchange = "periodChange();" })
<span class="icon"></span>
</div>
</div>
<div class="pull-left inline-block col-xs-5 col-sm-5 col-md-5 col-lg-5">
<div class="text-box-with-icon calendar margin-bottom10">
#Html.TextBoxFor(model => model.Periods[i].To, "{0:dd/MM/yyyy}", new { #class = "form-control period-to" })
<span class="icon"></span>
</div>
</div>
}
//some code
</div>
</div>
}
#*call the jquery.js file in the main or here*#
<script type="text/javascript">
$(document.ready(function(){
$('.period-from .period-to').change(function () {
alert("click");
//some code
});
});
</script>
this will fire the alert , but this is not enough for your case, you have to do more than this, as the list is generated in loop
your partial view should look like this, attaching the event after the C# code
Related
I am able to query database to properly fill calendar with events. I can drag and drop and the dates successfully update in database. If I click on existing event, the popup modal shows the details I want and I have been able to customize that easily.
However, I can't figure out how to create a new event from the fullCalendar view. I do not want to create it right there in a form in a modal, because I need to capture lots of extra selections from the user beyond the basics of start, end, id, color, etc. I just want to capture 'start' only and return a basic create view form.
When I track the breakpoint, everything looks like it is working. The 'start' value is passed to the controller method. That method calls to service to return a model. The breakpoint shows the view being rendered, but nothing actually changes on the screen. The js is below:
selectable: true,
select: function (start) {
selectedEvent = {
eventID: 0,
start: start,
allDay: true,
};
CreateFullCalEvent(start.toISOString());
$('#calendar').fullCalendar('unselect');
},
height: 'parent',
events: function (start, end, timezone, callback) {
$.ajax({
type: "GET",
contentType: "application/json",
url: "GetEventData",
dataType: "JSON",
success: function (data) {
var events = [];
$.each(data, function (i, data) {
events.push(
{
title: data.title,
start: moment(data.start),
end: moment(data.end),
allDay: true,
backgroundColor: data.color,
id: data.id,
textColor: data.textColor
}
);
});
callback(events);
}
})
},
nextDayThreshold: '00:00:00',
editable: true,
droppable: true,
nowIndicator: true,
eventClick: function (info) {
GetFullCalEventByID(info);
},
eventDrop: function (info) {
console.log(info);
UpdateFullCalEvent(info.id, info.start.toISOString(), info.end.toISOString());
},
eventResize: function (info) {
UpdateFullCalEvent(info.id, info.start.toISOString(), info.end.toISOString());
}
})
}
function CreateFullCalEvent(start) {
var object = {};
object.start = start;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "CreateFullCalEvent/",
dataType: "JSON",
data: JSON.stringify(object)
});
}
function GetFullCalEventByID(eventinfo) {
The controller method is here:
//CREATE
[HttpPost]
public ActionResult CreateFullCalEvent(string start)
{
//return RedirectToAction("Create", "CalendarEvent");
var model = _calEventSvc.FullCalendarEventCreateView(DateTime.Parse(start));
return View(model);
}
And the view:
#model CRM.Models.CalendarEvent.CalendarEventCreate
#{
ViewBag.Title = "CreateFullCalEvent";
}
<h2>CreateFullCalEvent</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Start, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Start, new { htmlAttributes = new { #class = "form-control", type = "date" } })
#Html.ValidationMessageFor(model => model.Start, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.End, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.End, new { htmlAttributes = new { #class = "form-control", type = "date" } })
#Html.ValidationMessageFor(model => model.End, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Title, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Title, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Title, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Location, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Location, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Location, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Details, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Details, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Details, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TypeOfEvent, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EnumDropDownListFor(model => model.TypeOfEvent, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TypeOfEvent, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" formaction="Create" class="btn btn-default" />
#*<input type="submit" value="Add Job info" formaction="Job" class="btn btn-default" />*#
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
I am not getting an error in visual studio or in debug mode in the browser. It is just not showing my view as expected. This is a regular view, not a partial view, so I am expecting my layout view from my other pages to show here.
The page I am on when I click on a date does not use a layout page and is like this:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="~/Content/fullcalendar.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<script src="~/Scripts/jquery-3.4.1.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/moment.js"></script>
<script src="~/Scripts/fullcalendar.js"></script>
<script src="~/Scripts/calendar.js"></script>
<script type="text/javascript">
$(document).ready(function () {
GetEventsOnPageLoad();
});
</script>
<style>
.calendar-body {
height: calc(100vh - 165px);
width: 90%;
padding-left: 130px;
}
.calendar-header {
padding-left: 30%;
margin-top: 5%;
}
body {
zoom: 110%;
background-image: url('../../Content/Assets/bgSubtle.jpg');
font-family: Consolas;
}
</style>
</head>
<body>
<div class="calendar-header">
#Html.Partial("~/Views/Shared/NavBarLayout.cshtml")
<div style="padding: 1%; margin-left: 71%;">#Html.ActionLink("List View", "Index", "CalendarEvent")</div>
</div>
<div class="calendar-body">
<div id="calendar"> </div>
</div>
<div id="MyPopup" class="modal fade modal-CreateEvent" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
#*Header*#
<div class="modal-header">
<h4 class="modal-title"></h4>
</div>
#*ModalBody*#
<div class="modal-body">
</div>
#*modal footer*#
<div class="modal-footer">
<button type="button" class="btn" data-dismiss="modal">
OK
</button>
<button id="btnEdit" class="btn btn-default pull-right">Edit</button>
</div>
</div>
</div>
</div>
</body>
</html>
You're calling CreateFullCalEvent via AJAX. That won't render your view unless you write some JavaScript to do so (and in that case you'd need a Partial View, not a full view, to go inside the existing page). Remember an AJAX request doesn't refresh the page automatically, it simply sends a request and receives a response. The response data (in this case the HTML of the view) comes back to the JavaScript inside a variable - what happens to that response data is then up to you and the code you write to process it. At the moment, your code is ignoring the response it gets back from the AJAX request.
You said you didn't want to put this Create form inside a modal, so I'll assume that you actually wanted redirect the browser away from the calendar and onto the Create page. To do that, a simple redirect is all you need:
function CreateFullCalEvent(start) {
window.location.href = "CreateFullCalEvent?start=" + encodeURIComponent(start);
}
But to make that work with the server-side code you'll also have to make the action method respond to GET instead of POST:
[HttpGet]
public ActionResult CreateFullCalEvent(string start)
Optionally you could also try changing it to CreateFullCalEvent(DateTime start) so you don't need to call DateTime.Parse later on.
P.S. Having said all that, it's not really clear why you feel a form inside a modal (overlaid on top of the calendar) wouldn't be suitable here - your "Create" view is only capturing a small number of fields. It seems to me it would work fine as a partial view. Just something to think about.
Can anyone help me with popover image preview, the problem is upon hovering the image preview wont display/update the selected image.
This is my field upon hovering the selected file image should display on popover.
as you can see below when i hover the first image it gives me the right image
but when i hover to the next image which should give me a desert image it still display the previous image
however it gives me the right output when i hover it again
Here is my code for popover
$('.example-popover').popover({
trigger: 'hover',
container: 'body',
html: true,
placement:'bottom',
content: function () {
var x = $(this).closest('div').find('#RawImage');
if (x[0].files && x[0].files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#img-prview').attr('src', e.target.result);
}
reader.readAsDataURL(x[0].files[0]);
}
return $('.img-container').html()
}
})
Here is my HTML
<div class="img-container hidden">
<img id="img-prview" src="#" style="width:50%"/>
</div>
<div class="form-group has-feedback">
<div class="row">
<div class="col-md-1">
Image
</div>
<div class="col-md-6">
#Html.TextBoxFor(m => m.RawImage, new { Class = "form-control", Placeholder = "Image",type="file" })
#Html.ValidationMessageFor(m => m.RawImage, null, new { Class = "text-danger" })
<i class="fa fa-image example-popover"></i>
</div>
</div>
</div>
<div class="form-group has-feedback">
<div class="row">
<div class="col-md-1">
Image
</div>
<div class="col-md-6">
#Html.TextBoxFor(m => m.RawImage, new { Class = "form-control", Placeholder = "Image",type="file" })
#Html.ValidationMessageFor(m => m.RawImage, null, new { Class = "text-danger" })
<i class="fa fa-image example-popover"></i>
</div>
</div>
</div>
I hope you can give me how can i preview the image on popover. Thanks
I already found a solution with this, but it has a delay.
I think the problem was the reader.onload it returns the img-container html first before changing the img src.
so this is what i did
$('.example-popover').popover({
trigger: 'hover',
container: 'body',
html: true,
placement:'bottom',
content: function () {
var x = $(this).closest('div').find('#RawImage');
var imgByte = '';
if (x[0].files && x[0].files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#previmg').attr('src', e.target.result);
}
reader.readAsDataURL(x[0].files[0]);
}
return '<img id="previmg" src="#" style="width:100%"/>'
}
})
Thanks everyone! Hopes this can be a reference for someone!
Issue : When user edit item from the list(in dialog form) and entered more than allowed symbols the dialog form changed it's size.(After validation error occurred (See screen attached)
How it opens in edit mode
After Validation error occurred, form size changed
View:
#model Maintenance.Models.AppVersion
#using (Html.BeginForm())
{
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Edit App Version</h4>
</div>
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.AppVersion1)
<div class="modal-body">
<div class="form-horizontal">
<div class="form-group margin-bottom">
#Html.LabelFor(model => model.AppVersionDescription, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.AppVersionDescription, new { htmlAttributes = new { #class = "form-control", autofocus = "" } })
#Html.ValidationMessageFor(model => model.AppVersionDescription, null, new { #class = "field-validation-error-tooltip" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input class="btn btn-primary" type="submit" value="Save changes" id="approve-btn" />
<button class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Layout:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - Moving Pro Services</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
#if (HttpContext.Current.User.Identity.IsAuthenticated)
{
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
#Html.ActionLink("Moving Pro Services", "Index", "Home", new {area = ""}, new {#class = "navbar-brand"})
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="dropdown">
Services <span class="caret"></span>
<ul class="dropdown-menu" role="menu">
<li>#Html.ActionLink("Companies", "Index", "Companies")</li>
<li>#Html.ActionLink("App Versions", "Index", "AppVersions")</li>
#if (User.Identity.IsAuthenticated)
{
if (User.IsInRole("Administrator"))
{
<li>#Html.ActionLink("Create User", "Register", "Account")</li>
}
}
</ul>
</li>
<li>#Html.ActionLink("About", "About", "Home")</li>
<li>#Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
#Html.Partial("_LoginPartial")
</div>
</div>
}
</div>
<div class="container body-content">
#RenderBody()
<hr/>
<footer>
<p>© #DateTime.Now.Year - Moving Pro Services</p>
</footer>
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
<div id='myModal' class='modal fade in'>
<div class="modal-dialog">
<div class="modal-content">
<div id='myModalContent'></div>
</div>
</div>
</div>
</body>
</html>
Script(Show dialog):
$(function () {
$.ajaxSetup({ cache: false });
$(document).on("click", ".modal-link", function (e) {
$('#myModalContent').load(this.href, function () {
$('#myModal').modal
(
{
keyboard: true
}, 'show'
);
bindForm(this);
});
return false;
});
$(document).on("click", "a[data-modal]", function (e)
{
$('#myModalContent').load(this.href, function ()
{
$('#myModal').modal
(
{
keyboard: true
}, 'show'
);
bindForm(this);
});
return false;
});
$(window.document).on('shown.bs.modal', '.modal', function () {
window.setTimeout(function () {
$('[autofocus]', this).focus();
}.bind(this), 100);
});
});
function bindForm(dialog) {
$('form', dialog).submit(function () {
var isValid = true; // assume all OK
$('form').validate(); // perform validation on the form
$('input[type="text"]').each(function (index, item) { // could change selector to suit e.g $('input, textarea').each(..
if (!$(this).valid()) {
isValid = false; // signal errors
return false; // break out of loop
}
});
if (!isValid) {
return false; // exit
}
$('#progress').show();
$.ajax({
url: this.action,
modal: true,
draggable: true,
resizable: false,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#myModal').modal('hide');
$('#progress').hide();
//location.reload();
alert(result.message);
}
});
return false;
});
}
Index:
#model Maintenance.Models.AppVersionsSearchModel
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h3>App Versions</h3>
#using (Html.BeginForm("index", "AppVersions", FormMethod.Get))
{
<div class="row">
<div class="form-horizontal">
<div class="col-lg-3">
#Html.TextBoxFor(m => m.AppVersion1, new { #class = "form-control", #placeholder = "App Version" })
</div>
<div class="col-lg-3" style="vertical-align: bottom;">
<input name="SearchButton" type="submit" value="Search" class="btn btn-primary" />
</div>
</div>
</div>
<div class="grid-control grid-control-app-version">
#{
var grid = new WebGrid(canPage: true,
rowsPerPage: Model.PageSize,
canSort: true,
ajaxUpdateContainerId: "grid"
);
grid.Bind(Model.AppVersions, rowCount: Model.TotalRecords, autoSortAndPage: false);
grid.Pager(WebGridPagerModes.All);
#grid.GetHtml(
fillEmptyRows: false,
tableStyle: "webgrid-table webgrid-table-app-version",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
alternatingRowStyle: "webgrid-alternating-row",
mode: WebGridPagerModes.All,
columns: grid.Columns(
grid.Column(header: "Action", canSort: false, style: "action",
format: #<text>
#Html.Raw("<a data-modal='' href='/AppVersions/Details/" + item.AppVersion1 + "' id='" + item.AppVersion1 + "' title='Detail'> <span class='glyphicon glyphicon-list-alt'> </span> </a>")
#Html.Raw("<a data-modal='' href='/AppVersions/Edit/" + item.AppVersion1 + "' id='" + item.AppVersion1 + "' title='Edit'> <span class='glyphicon glyphicon-edit'> </span> </a>")
#Html.Raw("<a data-modal='' href='/AppVersions/Delete/" + item.AppVersion1 + "' id='" + item.AppVersion1 + "' title='Delete'> <span class='glyphicon glyphicon-trash'> </span> </a>")
</text>
),
grid.Column(columnName: "AppVersion1", header: Sorter("AppVersion1", "App Version", grid), style: "AppVersion-AppVersion1"),
grid.Column(columnName: "AppVersionDescription", header: Sorter("AppVersionDescription", "App Version Description", grid), style: "AppVersion-AppVersionDescription"),
grid.Column(columnName: "CreateDate", header: Sorter("CreateDate", "Creation Date", grid), style: "AppVersion-CreateDate")
)
)
;
}
</div>
}
<div class="row">
<div class="form-horizontal">
<div class="col-lg-3">
#Html.ActionLink("Create New App Version", "Create", null, htmlAttributes: new { #class = "modal-link btn btn-primary", data_target = "#myModal", data_toggle = "myModal" })
</div>
</div>
</div>
#functions {
public static string Sorter(string columnName, string columnHeader, WebGrid grid)
{
return string.Format("{0} {1}", columnHeader, grid.SortColumn == columnName ?
grid.SortDirection == SortDirection.Ascending ? "▲" :
"▼" : string.Empty);
}
}
#section scripts{
#Scripts.Render("~/scripts/ProcessingModalDialog.js")
}
<script type="text/javascript">
$(function () {
$('th a, tfoot a').click(function () {
$('form').attr('action', $(this).attr('href')).submit();
return false;
});
});
</script>
If you look at the lines in your modal.
<div class="col-md-8">
#Html.EditorFor(model => model.AppVersionDescription, new { htmlAttributes = new { #class = "form-control", autofocus = "" } })
#Html.ValidationMessageFor(model => model.AppVersionDescription, null, new { #class = "field-validation-error-tooltip" })
</div>
When you run your code right click on the modal entry box and check the html generated. You will see that the EditorFor template and ValidationMessageFor become one line as the Validation is added into the as a .
You have a choice, you can style the Modal width and set a max-width class to your EditorFor entry to the wraps to the line underneath.
Or
You can put the ValidationMessageFor outside the Current block and try that.
I had a MVC 5 view which has a tab control. I have the following view
#using System.Collections
#using MyComp.Content.Text;
#using MyComp.Utilities;
#using System.Linq;
#model MyComp.Models.ViewModels.AdministratorViewModel
<style type="text/css">
...
</style>
<script src="~/Scripts/jquery-ui.js"></script>
<script src="~/Scripts/jquery-2.0.0.js"></script>
<div class="manage">
<ul class="nav nav-tabs" id="myTab">
<li class="active">
<a data-toggle="tab" href="#invite">
<span class="glyphicon glyphicon-inbox"></span>Invite
</a>
</li>
<li>
<a data-toggle="tab" href="#custom_invite">
<span class="glyphicon glyphicon-pencil"></span>Custom Invite
</a>
</li>
</ul>
<div class="tab-content">
<div id="invite" class="tab-pane active fade in">
#Html.Partial("_InvitePartial", Model)
</div>
<div id="custom_invite" class="htmlCode tab-pane fade">
#Html.Partial("_CustomInvitePartial", Model)
</div>
</div>
</div>
#section scripts {
<script>
function onSuccess(result) {
$('#notify_failure_message').html(result.notify_failure);
$('#notify_success_message').html(result.notify_success);
}
</script>
<script>
$(function () {
$("input[type=button]").click(function () {
var data_email = $('#email').val();
var data_product = $('#product option:selected').text();
$.ajax({
url: 'Tools/SendInvite',
type: 'POST',
data: { email: data_email, product: data_product },
success: function (result) {
$('#fail_message').html(result.result_failure);
$('#success_message').html(result.result_success);
}
});
});
});
</script>
}
and my partial view as
#using System.Collections
#using MyComp.Content.Text;
#using MyComp.Utilities;
#using System.Linq;
#model MyComp.Models.ViewModels.AdministratorViewModel
#using (Html.BeginForm("SendInvite", "Tools", FormMethod.Post,
new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h2>Invite Users</h2>
<div class="form-group">
#Html.LabelFor(m => m.EmailAddress, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.EmailAddress,
new { #class = "form-control", id = "email" })
#Html.ValidationMessageFor(m => m.EmailAddress)
</div>
</div>
<div class="form-group">
#Html.Label("Access To", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownList("Product", new SelectList(
new List<Object> {
new { Text = "ProcuctA", Value = "ProcuctA" },
new { Text = "ProcuctB", Value = "ProcuctB" },
new { Text = "All", Value = "All" }},
"Value",
"Text"),
new { #class = "form-control", id = "product" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<span id="fail_message" class="label label-danger"></span>
<span id="success_message" class="label label-success"></span>
#*<p class="text-info">Test Message</p>*#
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" id="invite_button" value="Invite User" class="btn btn-primary" />
</div>
</div>
}
Bu my button id="invite_button" won't fire the controller method. When I had everything in a single view it did fire and all was fine, this was using the same java script, why has this stopped working when I have moved to a partial view?
Thanks for your time.
Edit. my main view that hosts the partial views is
#using System.Collections
#using VisasysNET.Content.Text;
#using VisasysNET.Utilities;
#using System.Linq;
#model VisasysNET.Models.ViewModels.AdministratorViewModel
<style type="text/css">
span {
padding-right: 10px;
}
...
</style>
<script src="~/Scripts/jquery-ui.js"></script>
<script src="~/Scripts/jquery-2.0.0.js"></script>
<div class="manage">
<ul class="nav nav-tabs" id="myTab">
<li class="active">
<a data-toggle="tab" href="#invite">
<span class="glyphicon glyphicon-inbox"></span>Invite
</a>
</li>
<li>
<a data-toggle="tab" href="#custom_invite">
<span class="glyphicon glyphicon-pencil"></span>Custom Invite
</a>
</li>
</ul>
<div class="tab-content">
<div id="invite" class="tab-pane active fade in">
#Html.Partial("_InvitePartial", Model)
</div>
<div id="custom_invite" class="htmlCode tab-pane fade">
#Html.Partial("_CustomInvitePartial", Model)
</div>
</div>
</div>
#section scripts {
<script>
function onSuccess(result) {
$('#notify_failure_message').html(result.notify_failure);
$('#notify_success_message').html(result.notify_success);
}
</script>
<script>
$(function () {
$("input[type=button]").click(function () {
var data_email = $('#email').val();
var data_product = $('#product option:selected').text();
$.ajax({
url: 'Tools/SendInvite',
type: 'POST',
data: { email: data_email, product: data_product },
success: function (result) {
$('#fail_message').html(result.result_failure);
$('#success_message').html(result.result_success);
}
});
});
});
</script>
}
section's do not work within partial views,
see here:
Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine
invite_button does not have any javascript referencing it. Neither is it of type submit. This button will always do nothing.
It looks like you expect it to be of type submit.
<input type="submit" id="invite_button" value="Invite User" class="btn btn-primary" />
Try modifying the input button type from submit to button - it will work.. I tried with alert in a sample application and it worked.. for me. Below is the code.
Here's the MVC index view
<script type="text/javascript">
$(document).ready(function () {
$("input[type=button]").click(function () {
alert("hello from partial class");
});
});
</script>
<h2>#ViewBag.Message</h2>
<p>
To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">
http://asp.net/mvc</a>.
</p>
<div>
#Html.Partial("~/Views/Home/_MyTest.cshtml")
and here the partial view
#{
ViewBag.Title = "_MyTest";
}
<div>
<input type="button" id="invite_button" value="Invite User"/>
</div>
So on click on the button I am able to the jquery and alert popup's up
hope this helps..
you need to render scripts in your layout view.
<body>
<!-- Other Code -->
#RenderSection("scripts", required: false)
</body>
I have the following javascript which successfully puts the red border and green border according to bootstrap
Please check the lines with - (the lines relevant for this question)
(function ($) {
var defaultOptions = {
errorClass: 'has-error',
validClass: 'has-success',
validIcon: 'glyphicon glyphicon-ok form-control-feedback',
invalidIcon: 'glyphicon glyphicon-remove form-control-feedback',
highlight: function (element, errorClass, validClass, validIcon, invalidIcon) {
$(element).closest(".form-group")
.addClass(errorClass)
.removeClass(validClass);
debugger;
-$(element).next()
-.addClass(invalidIcon)
-.removeClass(validIcon);
},
unhighlight: function (element, errorClass, validClass, validIcon, invalidIcon) {
$(element).closest(".form-group")
.removeClass(errorClass)
.addClass(validClass);
debugger;
-$(element).next()
--.removeClass(invalidIcon)
--.addClass(validIcon);
}
};
$.validator.setDefaults(defaultOptions);
$.validator.unobtrusive.options = {
errorClass: defaultOptions.errorClass,
validClass: defaultOptions.validClass,
};
})(jQuery);
}
The razor view its like this:
<div class="form-group">
#Html.LabelFor(model => model.FechaHasta, new { #class = "col-sm-2 control-label" })
<div class="col-sm-10">
#Html.EditorFor(model => model.FechaHasta, new { htmlAttributes = new { #class = "form-control" } })
<span class="icon" aria-hidden="true"></span>
<div class="help-block">
#Html.ValidationMessageFor(model => model.FechaHasta)
</div>
</div>
</div>
Screenshot
Question: how can I dinamically add the glyphicons so that according to the boostrapframework when a field is valid it shows the green check and when its invalid it shows the red crosss.
http://screencast.com/t/Oat8DvZnsy
And it should show like this:
http://screencast.com/t/irp2fafnGx
http://getbootstrap.com/css/#forms
Change you HTML to
<div class="form-group has-feedback">
#Html.LabelFor(model => model.FechaHasta, new { #class = "col-sm-2 control-label" })
<div class="col-sm-10">
#Html.EditorFor(model => model.FechaHasta, new { htmlAttributes = new { #class = "form-control" } })
<span class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>
<span class="glyphicon glyphicon-warning-sign form-control-feedback" aria-hidden="true"></span>
<span class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true"></span>
<div class="help-block">
#Html.ValidationMessageFor(model => model.FechaHasta)
</div>
</div>
</div>
and add CSS like so
.form-group.has-feedback > .form-control-feedback {
display: none;
}
.form-group.has-success.has-feedback > .form-control-feedback.glyphicon-ok {
display: block;
}
.form-group.has-warning.has-feedback > .form-control-feedback.glyphicon-warning-sign {
display: block;
}
.form-group.has-error.has-feedback > .form-control-feedback.glyphicon-remove {
display: block;
}
You might have to play around with the HTML a bit - I wasn't sure that .icon was for and I removed it. Also, wasn't sure what your styling for the .help-block was.
Anyway what happens is that adding the classes .has-warning, .has-error, or .has-success to the form-group (via your validation script) shows the appropriate icon.