Here's my code:
<div class="center">
<p> Choose item:</p>
<div class="dropdown">
#using (Html.BeginForm("Start", "Home", FormMethod.Post, new { name = "form", id = "form" }))
{
#Html.DropDownListFor(x => x.SelectedId, #Model.ViewJaren,
new
{
onchange = "this.parentNode.form.submit()"
}
)
}
</div>
</div>
Been trying to get it to work but can't figure it out. I got the onchange to work with document.getElementById("form"). But there is no value passed. I get a blank page.
why not just separate it out.
<script>
$(document).ready(function(){
$('##Html.IdFor(x => x.SelectedId)').change(function(e){
$(this).closest('form').submit();
});
});
</script>
Related
I'm trying to show MeetingDiv when IsAnonymous is checked and when IsMeeting is checked, MeetingTextBox should be shown.
Tried .click, .change and live and nothing worked. I don't know where I'm wrong.
<div class="col-md-4 sidePad" >
#Html.Label("Is Anonymous")
#Html.CheckBoxFor(p => p.IsAnonymous, new { id = "CBAnonymous"})
</div>
<div class="col-md-6" id="MeetingDiv" style="display:none">
#Html.Label("Is Meeting")
#Html.CheckBoxFor(p => p.IsMeeting, new { id = "CBMeeting"})
</div>
<div class="col-md-6" id="MeetingTextBox" style="display:none">
#Html.Label("Meeting Name")
#Html.TextBoxFor(p => p.MeetingName, new { id = "TBMeetingName"})
</div>
<script>
$(function () {
$("#CBAnonymous").click(function () {
if ($(this).prop("checked")) {
$("#MeetingDiv").show();
} else {
$("#MeetingDiv").hide();
}
});
});
</script>
Try this
$('#CBAnonymous').change(function(){
if(this.checked)
$("#MeetingDiv").show();
else
$("#MeetingDiv").hide();
I have multiplebutton in one view for now.
For example, Admin and Student.
If I click the Adminbutton, the view will show a popup modal-dialog of the Admin registration form and the same goes to Student.
The following is the code that I written in cshtml:
#using (Html.BeginForm("Register", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="container">
-- the button | admin --
Admin Modal
<div class="modal fade" id="AdminModal" style="width:auto">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
×
<h3 class="modal-title" >Admin Modal</h3>
</div>
<div class="modal-body">
<form id="AdminForm">
-- with other textfields ---
-- and DropDownList for selecting User role, eg. Admin/Student --
</form>
</div>
<div class="modal-footer">
Cancel
<input type="reset" value="Submit" class="btn btn-success" id="btnSubmit" />
</div>
</div>
</div>
</div>
</div>
<div class="container">
-- the button | student --
Student Modal
<div class="modal fade" id="StudentModal" style="width:auto">
<div class="modal-dialog">--student form content--<div>
</div>
</div>
}
Provided with .Js:
$(document).ready(function () {
$("#btnSubmit").click(function () {
var AdminFormdata = $("#AdminForm").serialize();
$.ajax({
type: "POST",
url: "/Account/Register",
data: AdminFormdata,
success: function (d) {
console.log(d);
$("#AdminModal").modal("hide");
}
})
})
});
I tried with the Admin dialog, the above code does work to popup the particular dialog. However when I click the Submit button, it does not get the appropriate data from the chosen registration form. What is the problem here?
HTML does not allow to nest a <form> inside another <form>. Move the <div class="modal "> outside of the #using(Html.BeginForm) block.
Something like this:
#using (Html.BeginForm("Register", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary("", new { #class = "text-danger" })
Admin Modal
} #* close main form here! *#
<div class="modal fade" id="AdminModal" style="width:auto">
#* ... *#
<form id="AdminForm"> ... </form>
</div>
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'm trying to find the best method (any at this point) in which to keep page scroll position when deleting an item from a list using beginCollectionItem.
Initially I thought it was due to my other javascript/jQuery code in my main project (it still could be a factor), but when I recreated the situation in a new project only using the BCI code (index, two partials, controller, and model), when deleting an item from either of the lists, the page would jump to the top again, I really need (want) this to stop, how can I achieve this?
I have seen this question and the top answer I don't know how to properly implement or even if it's still valid, the second answer, using the below JS I have tested within my _Layout, within the budles which didn't fix the issue.
jQuery test
$(document).scroll(function () {
localStorage['page'] = document.URL;
localStorage['scrollTop'] = $(document).scrollTop();
});
$(document).ready(function () {
if (localStorage['page'] == document.URL) {
$(document).scrollTop(localStorage['scrollTop']);
}
});
Student Partial
#model UsefulCode.Models.Person
<div class="editorRow">
#using (Html.BeginCollectionItem("students"))
{
<div class="ui-grid-c ui-responsive">
<div class="ui-block-a">
<span>
#Html.TextBoxFor(m => m.firstName)
</span>
</div>
<div class="ui-block-b">
<span>
#Html.TextBoxFor(m => m.lastName)
</span>
</div>
<div class="ui-block-c">
<span>
<span class="dltBtn">
X
</span>
</span>
</div>
</div>
}
</div>
Teacher Partial
#model UsefulCode.Models.Person
<div class="editorRow">
#using (Html.BeginCollectionItem("teachers"))
{
<div class="ui-grid-c ui-responsive">
<div class="ui-block-a">
<span>
#Html.TextBoxFor(m => m.firstName)
</span>
</div>
<div class="ui-block-b">
<span>
#Html.TextBoxFor(m => m.lastName)
</span>
</div>
<div class="ui-block-c">
<span>
<span class="dltBtn">
X
</span>
</span>
</div>
</div>
}
</div>
Index
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
#model UsefulCode.Models.Register
<div id="studentList">
#using (Html.BeginForm())
{
<div id="editorRowsStudents">
#foreach (var item in Model.students)
{
#Html.Partial("StudentView", item)
}
</div>
#Html.ActionLink("Add", "StudentManager", null, new { id = "addItemStudents", #class = "button" });
}
</div>
<div id="teacherList">
#using (Html.BeginForm())
{
<div id="editorRowsTeachers">
#foreach (var item in Model.teachers)
{
#Html.Partial("TeacherView", item)
}
</div>
#Html.ActionLink("Add", "TeacherManager", null, new { id = "addItemTeachers", #class = "button" });
}
</div>
#section scripts {
<script type="text/javascript">
$(function () {
$('#addItemStudents').on('click', function () {
$.ajax({
url: '#Url.Action("StudentManager")',
cache: false,
success: function (html) { $("#editorRowsStudents").append(html); }
});
return false;
});
$('#editorRowsStudents').on('click', '.deleteRow', function () {
$(this).closest('.editorRow').remove();
});
$('#addItemTeachers').on('click', function () {
$.ajax({
url: '#Url.Action("TeacherManager")',
cache: false,
success: function (html) { $("#editorRowsTeachers").append(html); }
});
return false;
});
$('#editorRowsTeachers').on('click', '.deleteRow', function () {
$(this).closest('.editorRow').remove();
});
});
</script>
}
Aside from inflicting pain to myself for how dense I now feel I am relieved.
Adding return false; to the delete action resolves this, it was present on the add action but from staring at it for hours I just assumed it was there.
If there is a better answer, please put it in as this will only work on this section of code.
Below is the answer code:
$('#addItemStudents').on('click', function () {
$.ajax({
url: '#Url.Action("StudentManager")',
cache: false,
success: function (html) { $("#editorRowsStudents").append(html); }
});
return false;
});
$('#editorRowsStudents').on('click', '.deleteRow', function () {
$(this).closest('.editorRow').remove();
return false; // add this
});
I recently added jquery references to a project, and now the Post from a View is not triggering. The Post ActionResult saved user-chosen settings, and now a break point inside the Post isn't being hit. There's no error in Visual Studio, but Chrome's Console outputs the warnings "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/." and "Setting 'XMLHttpRequest.withCredentials' for synchronous requests is deprecated."
The code ran before jquery, so is the problem related to those warnings, some other aspect of jquery, or possibly something else? Suggestions here, here, and here offer possible solutions to the asynchronous warnings, but would, say, adding async to the new declarations in the Layout trigger the Post again? Thanks in advance to all.
The View:
#using Project.Data
#model Project.Models.PreferencesModel
#{
ViewBag.Title = "Preferences";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="page_bar clearfix">
<div class="row">
<div class="col-md-8">
<h1 class="page_title">
<i class="fa fa-gears"></i> Preferences
</h1>
</div>
</div>
<div class="page_content">
<div class="container-fluid">
<form data-parsley-validate>
#using (Html.BeginForm("Preferences", "Manage", FormMethod.Post, new { id = "PreferencesForm", autocomplete = "on", data_parsley_validate = "data-parsley-validate" }))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(m => m.PreferenceID)
#Html.HiddenFor(m => m.PreferenceCreatedBy)
#Html.HiddenFor(m => m.PreferenceCreatedDate)
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-body">
<div class="col-md-4">
#Html.LabelFor(m => m.PricingPreferenceTypeID, "Pricing Preference Type")
#Html.DropDownListFor(m => m.PricingPreferenceTypeID, StaticCache.GetPricingPreferenceTypes(), new { #class = "form-control", data_parsley_required = "true" })
#Html.ValidationMessageFor(m => m.PricingPreferenceTypeID)
</div>
<div class="col-md-4">
#Html.LabelFor(m => m.PricingStrategyID, "Pricing Strategy")
#Html.DropDownListFor(m => m.PricingStrategyID, StaticCache.GetPricingStrategies(), new { #class = "form-control", data_parsley_required = "true" })
#Html.ValidationMessageFor(m => m.PricingStrategyID)
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12 text-right">
<button type="submit" class="btn btn-success btn-large">Save</button>
</div>
</div>
}
</form>
</div>
</div>
The Layout contains these new declarations:
<script src="~/Scripts/jquery-2.1.3.js"></script>
<script src="/Scripts/jquery-ui-1.11.4.js"></script>
Finally, the previously working Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Preferences(PreferencesModel model)
{
ProjectEntities projectDb = new ProjectEntities();
projectDb.uspAddPreference(DateTime.Now, model.PricingStrategyID, null, null, model.PricingPreferenceTypeID);
return RedirectToAction("Preferences");
}
EDIT
This piece of jquery was added to the bottom of the View to make one dropdown dependent on the other, but the break point inside the HttpPost ActionResult is still not hit. What could be causing this?
#section Scripts{
<script>
$(function () {
var $dropdownInput = $("#PricingStrategyID");
$("#PricingPreferenceTypeID").change(function () {
if (this.value != 1) {
$dropdownInput.hide();
} else {
$dropdownInput.show();
}
}).change();
});
</script>
}
2nd EDIT
Save button included in original view.
The answer to this seems to be a nested form tag that eluded detection. Once it was removed, the Post worked fine.