I have a MVC beginform (with JQUERY UI MOBILE AND AJAX.) When the user clicks submit,
I would like **<div data-role="page" id="two">** to display on the page.
#using (Html.BeginForm())
{
<div data-role="page" id="one">
<div data-role="header">Header stuff</div><!-- /header -->
<div data-role="content" >
<div class="ui-body ui-body-b">
.....DATA......
<input type="submit" value="Submit" />
</div></div><div>
<div data-role="page" id="two">
<div data-role="header">Header stuff2</div><!-- /header -->
<div data-role="content" >
<div class="ui-body ui-body-b">
FINISH
</div></div><div>
}
I just ran into this and found out I cannot return the anchor tag from MVC's controllers. So, I redirect users from a parameter that the controller passes back:
if( getParameterByName("anchorID") != null) {
location.href = '#' + getParameterByName("anchorID");
}
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)')
.exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
Then you should be able to get your div to view after clicking the submit.
Related
Is there anyway to navigate to next tab after submitting form in first tab in asp.net razor pages.
Currently im using return page() ,which will load first form.
You can overrride your form submit with Jquery and after submit you can change tab with jquery.
$("#yourFormId").submit(function (event) {
event.preventDefault();
var post_url = $(this).attr("action"); //get form action url
var request_method = $(this).attr("method"); //get form GET/POST method
var form_data = $(this).serialize(); //Encode form elements for submission
$.ajax({
url: post_url,
type: request_method,
data: form_data
}).done(function (response) { //
// switch tab here
});
});
Is there anyway to navigate to next tab after submitting form in first tab in asp.net razor pages.
It seems that you are using Bootstrap navigation tabs in your Razor pages. To achieve the above requirement, you can try the following approaches.
Approach 1: store active tab info in localStorage while user click the submit button, then you can activate specific tab based on stored active tab info via JavaScript, like below.
<!-- Tab panes -->
<div class="tab-content">
<!-- STAFF DETAILS -->
<div role="tabpanel" class="tab-pane active" id="StaffDetails">
<br />
<form method="post" asp-page-handler="InsertStaffDetails">
Staff Details Partial Here
#*<partial name="_StaffDetails" />*#
<div style="float:right">
<input type='submit' class='btn btn-success' value='Save' onclick="setNextActiveTabFunc('Biodata')"/>
</div>
</form>
</div>
<!-- BIODATA -->
<div role="tabpanel" class="tab-pane" id="Biodata">
<br />
<form method="post" asp-page-handler="InsertBioData">
Bio Data Partial Here
#*<partial name="_BioData" />*#
<div style="float:right">
<input type='submit' class='btn btn-success' value='Save' onclick="setNextActiveTabFunc('EduQualification')" />
</div>
</form>
</div>
<!-- EDUCATIONAL QUALIFICATION -->
<div role="tabpanel" class="tab-pane" id="EduQualification">
<br />
<form method="post" asp-page-handler="InsertEduDetails">
Edu Details Partial Here
#*<partial name="_EduQualification" />*#
<div style="float:right">
<input type='submit' class='btn btn-success' value='Save' onclick="setNextActiveTabFunc('Assets')" />
</div>
</form>
</div>
#*do same on other submit button*#
JS code
<script>
function setNextActiveTabFunc(atab) {
localStorage.setItem("activeTab", atab);
}
$(function () {
var active_tab = localStorage.getItem("activeTab");
//remove localStorage item
//localStorage.removeItem("activeTab");
if (active_tab != "" && active_tab != null) {
$('#wizard a[href="#' + active_tab+'"]').tab('show');
} else {
$('#wizard a[href="#StaffDetails"]').tab('show');
}
})
</script>
Approach 2: Can achieve same by checking handler name through QueryString, then dynamically set active tab on client side.
$(function () {
var urlParams = new URLSearchParams(window.location.search);
var pre_handler = urlParams.get('handler');
switch (pre_handler) {
case "InsertStaffDetails":
//console.log("InsertStaffDetails");
$('#wizard a[href="#Biodata"]').tab('show');
break;
case "InsertBioData":
$('#wizard a[href="#EduQualification"]').tab('show');
break;
case "InsertEduDetails":
$('#wizard a[href="#Assets"]').tab('show');
break;
//...
//code for other tabs
//..
default: $('#wizard a[href="#StaffDetails"]').tab('show');
}
})
Test Result
I am working on an asp.net core mvc web application, and i have added the following field to show google recaptcha version 2:-
<div class="form-group">
<div class="col-md-2"></div>
<div class="col-md-10">
<div class="g-recaptcha" data-callback="recaptchaCallback" data-sitekey="#ViewData["ReCaptchaKey"]">
</div>
</div>
</div>
//code goes here
#section Scripts {
<script src='https://www.google.com/recaptcha/api.js'></script>}
and inside my action method i am checking if the user select the recaptcha or not, as follow:-
public async Task<IActionResult> SearchNPI(ContactinfoCreate ci)
{
//add uncompleted entry
ViewData["ReCaptchaKey"] = _configuration.GetSection("GoogleReCaptcha:key").Value;
if (!ReCaptchaPassed(
Request.Form["g-recaptcha-response"], // that's how you get it from the Request object
_configuration.GetSection("GoogleReCaptcha:secret").Value,
_logger
))
{
ModelState.AddModelError(string.Empty, "Please enter CAPTCHA");
}
but on the client side how i can ake the recaptcha required filed, so the user can not submit the form unless he/she select the recaptcha?
You can determine whether clicks recaptcha before submit by triggering the data-callback method of recaptcha, and then adding a hidden control.
After clicking recaptcha,assign a value to hidden control in data-callback method, and then judge the hidden value in the form submit method to determine whether this form can be submitted.
<form method="post">
<div class="form-group">
<div class="col-md-2"></div>
<div class="col-md-10">
<div class="g-recaptcha" data-sitekey="#ViewData["ReCaptchaKey"]" data-callback="recaptchaCallback"></div>
<input type="hidden" value="" id="isClickCaptcha" />
<span class="text-danger" id="validationText"></span>
</div>
</div>
<input id="Submit1" type="submit" value="submit" />
</form>
<script src="https://www.google.com/recaptcha/api.js?hl=en-US"></script>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script>
var recaptchaCallback = function () {
$("#isClickCaptcha").val("yes");
};
$("form").submit(function () {
if ($("#isClickCaptcha").val() == "") {
event.preventDefault();
$("#validationText").text("Please enter CAPTCHA!");
return false;
}
})
</script>
Here is the test result:
in javascript I imagine you have a function called recaptchaCallback which is responsible to perform the form submit. It should look like this
function recaptchaCallback(token) {
}
well, just add
if (!token || token === '') {
alert("Could not verify that you are a human");
return;
}
I have a view partial in a strongly typed controller. Is it possible to render the would-be contents of that view partial on mouseclick?
Example:
Active View
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<div id="modalView"></div>
<script>
$(document).ready(function () {
$('.open-popup-link').magnificPopup({
key: 'my-popup',
type: 'inline',
inline: {
// Define markup. Class names should match key names.
markup: '<div class="white-popup"><div class="mfp-close"></div>awesome</div>'
}
},
{
callbacks: {
open: function(){
}
}
});
$('.open-popup-link').on('mfpOpen', function(e /*, params */) {
var linkText = // how to I grab this? (e.g. 1, 2, 3, or 4)
$.ajax({
// call view partial withlinktext as parameter
//on success
// var inlineContent = viewPartialContent
// On error
// var inlineCOntent = 'Uh oh, something went wrong'
});
});
});
</script>
View Partial
#model *******.Models.Reservation
<div class="container">
<div class="section-heading">
<h2 class="red">Confirm Your Reservation</h2><br />
</div>
<div class="section-content">
<div class="row">
<h3 class="black text-center">Are you sure you want to reserve space <span class="dark-red">#Model.SpaceNumber</span></h3>
<h4 class="black text-center">for <span class="dark-red">#Model.Game.Description</span> on <span class="dark-red">#Model.Game.Date.ToShortDateString()</span>?</h4>
</div>
<div class="row">
<div class="hero-buttons text-center">
No
<form action="/api/Reservations" method="post" id="confirmationForm">
#Html.Hidden("eRaiderUserName", #Model.eRaiderUserName)
#Html.Hidden("SpaceNumber", #Model.SpaceNumber)
<input type="submit" value="Yes" class="btn btn-red btn-lg white">
</form>
</div>
</div>
</div>
</div>
Method for viewpartial in controller
public ActionResult Confirm(int spaceNumber)
{
var reservation = new Reservation { SpaceNumber=spaceNumber, UserName=AppSettings.CurrentUserName, Game=db.Games.FirstOrDefault(g => g.ID == AppSettings.CurrentGameID) };
return View(reservation);
}
Does this make sense, and can I make it work?
You need to do two things:
change your Confirm method, so that it returns PartialView(reservation) instead of View(reservation)
You need to use AJAX, for example jQuery ajax, to get the HTML, and render it in your page
$.ajax({url = 'the url for your Confirm action',
type = 'GET',
dataType='html',
data = params}).done(function(html) {
// use the jQuery and the html to inject it wherever you need in your page
});
NOTE: params is a jQuery object which contains the data you need to pass like spaceNumber in this case, i.e.
var params = { spaceNumber: 'spaceNumberValue' }
I have control for user authorization which includes form, two textboxes and submit button.
This control included in the master page through RenderAction method.
I have registration page (its view included through RenderBody method) also with form. When I submit data from the registration form, the login control is triggered also and its handler (controller method for handling POST data) is called. Below you can see controller methods for authorization.
How can I prevent sending POST data to the login control after submitting data from other forms?
[HttpPost]
public RedirectResult LogIn(AuthViewModel authResult)
{
if (ModelState.IsValid)
{
userService.LogInUser(authResult.Login, authResult.Password, Request.UserHostAddress);
}
else
{
TempData["AuthMessage"] = GetValidationMessage();
}
string redirectUrl = "/";
if (Request.UrlReferrer != null)
{
redirectUrl = Request.UrlReferrer.AbsoluteUri.ToString();
}
return Redirect(redirectUrl);
}
[HttpGet]
[ChildActionOnly]
public PartialViewResult LogIn()
{
if (userService.IsUserLoggedIn())
{
User currentUser = userService.GetLoggedInUser();
ViewBag.LoggedInMessage = currentUser.FullName + "(" + currentUser.Login + ")";
}
return PartialView("AuthControl");
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>#ViewBag.Title</title>
</head>
<body>
<div>
<div id="header">
<div>
<div>
#{Html.RenderPartial("SearchControl");}
</div>
</div>
</div>
<div id="right_menu">
<div>
#{Html.RenderAction("LogIn", "Navigation");}
</div>
#{Html.RenderAction("Menu", "Navigation");}
<div>
#{Html.RenderAction("Index", "Messages");}
</div>
<div>
#{Html.RenderAction("TagCloud", "Navigation");}
</div>
</div>
<div id="main_content">
#RenderBody()
</div>
<div id="footer">
</div>
</div>
</body>
</html>
AuthControl:
#model AuthViewModel
<div class="rounded-corners auth-panel">
#if (ViewBag.LoggedInMessage == null)
{
<div class="auth-container">
#using (Html.BeginForm("LogIn", "Navigation"))
{
<div>
<label for="Login">
Login:
</label>
#Html.TextBoxFor(m => m.Login, new { #class="middle-field"})
</div>
<div>
<label for="Password">
Password:
</label>
#Html.PasswordFor(m => m.Password, new { #class="middle-field"})
</div>
<div class="in-center">
<input type="image" src="#Url.Content("~/Content/Images/submit.png")"/>
</div>
}
</div>
<div class="error-msg">
#if (TempData["AuthMessage"] != null)
{
#Html.Raw(TempData["AuthMessage"].ToString())
}
#Html.ValidationSummary()
</div>
<div class="small-nav-message">
Registration
</div>
}
</div>
Registration page:
RegistrationViewModel
#{
ViewBag.Title = "Registration";
}
#if (TempData["RegistrationFinished"] == null || !(bool)TempData["RegistrationFinished"])
{
<div class="post content-holder">
<div class="fields-holder">
<div >
<div class="error-msg">
#if (TempData["ValidationMessage"] != null)
{
#Html.Raw(TempData["ValidationMessage"].ToString())
}
</div>
#using (Html.BeginForm())
{
<span>
Email:
</span>
<span>
#Html.TextBoxFor(v => v.Email)
</span>
<span>
Password:
</span>
<span>
#Html.PasswordFor(v => v.Password)
</span>
<input type="submit" value="Register"/>
}
</div>
</div>
</div>
}
else
{
<div>
Activation link was sent to your email.
</div>
}
In the Registration view, change
#using (Html.BeginForm())
to
#using (Html.BeginForm("Index", "Registration"))
In a single controller, single Action scenario, the extra specific routing information is not required, but obviously the routing engine can't figure out on it's own which controller/action to route to with multiple controllers/actions.
Edit based on comments:
So this is a routing problem. Try adding a specific route for your Registration action. Something like
routes.MapRoute(
"Register", // Route name
"{controller}/Index/{registrationResult}", // URL with parameters
new {
controller = "{controller}",
action = "Selector",
registrationResult= UrlParameter.Optional
}
);
'registrationResult' would be the name of the parameter in the post Action. I'm thinking that the view models are so similar the routing engine can't differentiate between the two. Add the above route before the default route and it should match it when the registration form is submitted.
To solve my problem I check IsChildAction property from the controller context. Also I have to clear the model state.
[HttpPost]
public ActionResult LogIn(AuthViewModel authResult)
{
if (!this.ControllerContext.IsChildAction)
{
if (ModelState.IsValid)
{
userService.LogInUser(authResult.Login, authResult.Password, Request.UserHostAddress);
}
else
{
TempData["AuthMessage"] = GetValidationMessage();
}
string redirectUrl = "/";
if (Request.UrlReferrer != null)
{
redirectUrl = Request.UrlReferrer.AbsoluteUri.ToString();
}
return Redirect(redirectUrl);
}
ModelState.Clear();
return PartialView("AuthControl");
}
I'm trying to refresh a partial view inside of a view when a form is submitted. However, whenever I try it just renders the partial view as a normal view. Can someone tell me what I'm doing wrong?
Controller:
public ActionResult ChangeHeatName(string heatName, string updatedHeat)
{
string user = User.Identity.Name;
HomeModel H = new HomeModel();
H.ChangeHeatName(heatName, updatedHeat, user);
ChemViewModel mySlagViewModel = new ChemViewModel();
mySlagViewModel = H.QueryResults(heatName);
return PartialView("PartialChemAnalysis", mySlagViewModel);
}
Partial view form (contained in partial view, not main view):
#using (Ajax.BeginForm("ChangeHeatName", "Home", new AjaxOptions(){UpdateTargetId = "chemDiv" InsertionMode = InsertionMode.Replace}))
{
<section>
Heat Name:<input type="text" name="heatName" value="#Html.ValueFor(x => x.heatname)" style ="width:100px"/>
Change to:<input type="text" name="updatedHeat" value="" style="width: 100px" />
<input type="submit" name="ChangeHeatName" value="Change" />
</section>
}
Index view where partial view is being rendered:
#if(ViewBag.SearchKey == null)
{
<div class="content-wrapper">
<hgroup class="title">
<h1>#HttpContext.Current.User.Identity.Name</h1>
<h2>#ViewBag.Message</h2>
</hgroup>
</div>
}
#using (Html.BeginForm("Index", "Home", "POST"))
{
<div class="searchField">
<input type="text" class="search-query" name="heatSearch" placeholder="Search">
<button class="btn btn-success" type="submit">Search</button>
<br />
#if (ViewBag.AverageSuccessful == true)
{
<input type="text" name="AvgConfirmation" class="search-query" value="Average Submitted Successfully" width:"400px" placeholder="Search" />
}
</div>
}
#if(ViewBag.SearchKey != null)
{
<div>
<div id ="chemDiv">
#Html.Action("PartialChemAnalysis", "Home", (string)ViewBag.SearchKey)
</div>
<div id ="slafDiv">
#Html.Action("PartialSlagView", "Home", (string)ViewBag.SearchKey)
</div>
</div>
}
Index controller that passes SearchKey:
[HttpPost]
public ActionResult Index(string heatSearch)
{
ViewBag.SearchKey = heatSearch;
return View();
}
Currently your ajax.beginform is in your partial view, that's all fine and dandy, but your partialview is not rendered inside your index, so really your never doing the ajax replace logic you're just calling a the action method and getting a full page refresh of the partial view.
here's what would work.
#if(ViewBag.SearchKey != null)
{
<div>
<div id ="chemDiv">
#Html.Partial("ChangeHeatName")
</div>
<div id ="slafDiv">
#Html.Action("PartialSlagView", "Home", (string)ViewBag.SearchKey)
</div>
</div>
}
Now your Ajax.Beginform is rendered in the index view, and when the button is clicked it will refresh.
Edit: you'll need to do something with #Html.Action("PartialChemAnalysis", "Home", (string)ViewBag.SearchKey) possibly stick it in your partial view, because everything in "chemDiv" will now be replaced upon update.
You're not specifying POST in Ajax.BeginForm(). Try this:
#using (Ajax.BeginForm("ChangeHeatName", "Home", FormMethod.Post,
new AjaxOptions(){UpdateTargetId = "chemDiv" InsertionMode = InsertionMode.Replace}))
{...}
Also, stick a breakpoint on your controller action and step through it, see if it's actually hitting return PartialView() or skipping over it.
Posting this because it's not an intuitive fix. Apparently there are issues with MVC 4 and jQuery 1.9.1 so to get this to work I had to change my reference to jQuery 1.7.1