I have a Partial View in my Layout page which contain a Form. The partial view open as popup. After submitting form I have to return back to the current page with opened popup and a success message should appear there but I am not able to return back to the right view.
My Layout Page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>#ViewBag.Title || Midas WebSite</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/site")
#Scripts.Render("~/bundles/modernizr")
<script type="text/javascript" language="javascript">
/* Superior Web Systems */
function displayHideBox(boxNumber) {
if (document.getElementById("LightBox" + boxNumber).style.display == "none") {
$("#LightBox" + boxNumber).fadeIn();
$("#grayBG").fadeIn();
} else {
$("#LightBox" + boxNumber).fadeOut();
$("#grayBG").fadeOut();
}
}
</script>
</head>
<body>
<div id="grayBG" class="grayBox" style="display:none;"></div>
<div id="LightBox1" class="box_content" style="display:none;">
<div onclick="displayHideBox('1'); return false;" class="close">X</div>
#Html.Action("ActionToBindPartialView", "ControllerName")
</div>
#RenderBody()
#RenderSection("scripts", required: false)
#Scripts.Render("~/bundles/jqueryval")
My Partial View
<div id="divActions">
// My Form Here
#Ajax.ActionLink("Submit", "ActionName", "ControllerName", new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "divActions",
OnSuccess = "onSucess()"
})
</div>
Now my action code which I have tried so far:
1.
// My Code
return PartialView("MyPartialView");
2
// My Code
return PartialView("MyPartialView", MyModel);
3
// My Code
return View();
4
// My Code
return ParialView();
I am a beginner and not able to find what I am doing wrong. Please suggest what should I do to make this work.
It is hard to say what you are doing wrong, due to the limited workspace that we have to discuss the problem. However here is a working example that may help you, please follow each step:
Bundles
bundles.Add(new ScriptBundle("~/bundles/jquery")
.Include("~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval")
.Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
HomeController
public ActionResult Index()
{
return View();
}
public PartialViewResult GetPartial()
{
return PartialView("_MyPartial");
}
Index.cshtml
<h2>Index</h2>
<div id="divActions">
#Ajax.ActionLink("Submit", "GetPartial", "Home", new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "divActions",
OnSuccess="onSuccess()"
})
</div>
<script type="text/javascript">
function onSuccess()
{
alert("Success!");
}
</script>
_MyPartial.cshtml
<h2>_MyPartial</h2>
_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<title>#ViewBag.Title</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
#RenderBody()
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
#RenderSection("scripts", required: false)
</body>
</html>
To confirm the rendered scripts in the page source (in the browser):
<script src="/Scripts/jquery-1.8.2.js"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
As you can see, there is nothing hard about it. You just need to follow the steps above.
I hope it helps.
Hint: check for other scripts errors, maybe your custom code to show the popup is causing a error. Double check if you are rendering javascript inside the partial view. Consider extract it to the regular view.
Related
I have one page called Page1 which have a button.
<button onclick="redirecttodivofotherpage(); "></button>
The other Page2 have 3 Div
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
I want to redirect to div3 on button click of Page1 button.
How to do it with controller or jquery.
You could try something like this:
<button class="js-btn"></button>
$(function(){
$(".js-btn").on("click",function(){
window.location = "..../#div3";
});
})
The string "..../#div3" represent the relative url of your page and at the end has a #div3. This way, using window.location, you would be redirected to the page you want and using #div3 to the section you want.
This can be done with cookies. Setting a cookie with id you want to scroll, and then, when the new page is loaded, read the cookie and scroll to defined id. I used the very popular plugin jquery-cookie.
Check this sample solution Note: Click on Events to nav to the other page.
**http://plnkr.co/edit/hBJj69nP6kvrEuoCVw3k?p=preview**
try this working demo, that will work
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<button class="click">Click Me</button>
<div id="mydiv" style="border:2px solid black;width:800px;height:900px; background-color:orange; position:absolute;top:1000px;margin:20px;">
hello anuradh
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$(".click").on('click',function(){
window.location = "#mydiv";
});
});
</script>
</body>
</html>
or else you can scroll it nicely like this
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<button class="click">Click Me</button>
<div id="mydiv" style="border:2px solid black;width:800px;height:900px; background-color:orange; position:absolute;top:1000px;margin:20px;">
hello anuradh
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$(".click").on('click',function(){
//window.location = "#mydiv";
$('html, body').animate({
scrollTop: $("#mydiv").offset().top
}, 2000);
});
});
</script>
</body>
</html>
Use a window.location.hash to scroll to the element with the id
<button class="js-btn"></button>
$(function(){
$(".js-btn").on("click",function(){
window.location.hash = "#div3";
});
});
Try this, it works for me:
<a class="className">link</a>
$(".className").on("click", function () {
window.location = "yourPage.html#divId";
});
In webforms I'd do
<script type="text/JavaScript">
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);", timeoutPeriod);
}
</script>
<body onload="JavaScript:timedRefresh(5000);">
or codebehind Page_Load
Response.AddHeader("Refresh", "5");
Question How to make the screen refresh every 5 seconds in ASP.NET MVC3
You could do the same in MVC:
<script type="text/javascript">
function timedRefresh(timeoutPeriod) {
setTimeout(function() {
location.reload(true);
}, timeoutPeriod);
}
</script>
<body onload="JavaScript:timedRefresh(5000);">
...
</body>
or using a meta tag:
<head>
<title></title>
<meta http-equiv="refresh" content="5" />
</head>
<body>
...
</body>
or in your controller action:
public ActionResult Index()
{
Response.AddHeader("Refresh", "5");
return View();
}
I am using asp.net MVC 5.
I have a _layout file as follows:
<!DOCTYPE html>
<html lang="en">
<head>
#Html.Partial("_Head")
#RenderSection("styles", required: false)
</head>
<body>
#RenderBody()
#RenderSection("scripts", required: false)
</body>
</html>
I then have my main view:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
Title = "mainView"
}
<div class="partialcontents" data-url="/user/UserList"></div>
$(document).ready(function (e) {
$(".partialcontents").each(
function (index, item) {
var url = $(item).data("url");
if (url && url.length > 0) {
$(item).load(url, function () { $(this).css("background-image", "none"); });
}
}
);
});
and here is my partial view:
#{
}
<p> Partial View</p>
#section scripts
{
#Scripts.Render("~/bundles/script/datatable")
}
My controller that renders the partial view:
[Authorize]
public ActionResult UserList(UsersViewModel model, string sortOrder, string currentFilter, string searchString, int? page)
{
.... removed for simplicity
return PartialView("_UserList", new UsersViewModel()
{
Users = users.ToPagedList(pageNumber, pageSize)
});
}
So now my issue is that the section from the partial view is not being rendered in the main layout file. I understand why I think...
Its because I am rendering it in another controller. and then passing it along.
But how can I get this right?
You should place:
#section scripts
{
#Scripts.Render("~/bundles/script/datatable")
}
in the main view, because AJAX requests return only partial without layout so MVC doesn't know where it should render this script section. In this AJAX request #RenderSection("scripts", required: false) is never evaluated. If you omit #section scripts in your partial, it would probably work, but this is a not good approach to include JS in AJAX responses, so don't do that if you don't need too.
How to add link to JavaScript file into the header of the certain ASP .NET MVC page?
Lets say there are _Layout.cshtml and About.cshtml and I need to put some javascript file to the header of the About.cshtml. I mean to that page only.
http://www.dotnetcurry.com/ShowArticle.aspx?ID=636
How it can be done?
Why must it be in the header? You can include any script you need inline:
<script src="#Url.Content("~/Scripts/jquery-ui.min.js")" type="text/javascript"></script>
My solution:
_Layout.cshtml
!DOCTYPE html>
<html>
<head>
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
#if (IsSectionDefined("AddToHead"))
{
#RenderSection("AddToHead", required: false)
}
</head>
About.cshtml
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#section footer {
<b>Footer Here</b>
}
#section AddToHead {
<script src="#Url.Content("~/Scripts/test.js")" type="text/javascript">
</script>
}
Try below code
HtmlGenericControl my_js = new HtmlGenericControl("script");
my_js.Attributes["async"] = "async";
my_js.Attributes["type"] = "text/javascript";
my_js.Attributes["src"] = "http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js";
Page.Header.Controls.Add(my_js);
You need to use namespace : "using System.Web.UI.HtmlControls" to use HtmlGenericControl.
I am having an issue where form errors are persisting on the page even after the form is valid.
I have the following setup:
_Layout.cshtml:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
</head>
<body>
#RenderBody()
</body>
</html>
index.cshtml:
#model SimpleForm.Models.Name
#{
ViewBag.Title = "Form";
}
<script>
$().ready(function () {
$("#quote_form").submit(function () {
return true;
});
});
</script>
#using (Ajax.BeginForm("RunQuote", "Page", new AjaxOptions { UpdateTargetId = "quoteSummary" }, new { id = "quote_form", onreset = "return confirm('Clear all form data?')" }))
{
<input type="submit" value="Send" />
<fieldset>
<legend>Name </legend>
<dl>
<dt>First</dt>
<dd>#Html.TextAreaFor(m => m.first, new { onblur = "$('#quote_form').submit();" })</dd>
<dt>Last</dt>
<dd>#Html.TextAreaFor(m => m.last, new { onblur = "$('#quote_form').submit();" })</dd>
</dl>
</fieldset>
<div class="qMatrixSubText">
#Html.ValidationSummary()
#{
Html.ValidateFor(m => m.first);
Html.ValidateFor(m => m.last);
}
</div>
<div id="quoteSummary" class="quoteSummary">
</div>
}
FormController.cs
using System;
using System.Web.Mvc;
using SimpleForm.Models;
namespace SimpleForm.Controllers
{
public class FormController : Controller
{
//
// GET: /Form/
public ActionResult Index()
{
return View();
}
public String RunQuote(Name quote)
{
return "Success!";
}
}
}
Name.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace SimpleForm.Models
{
public class Name
{
[Required()]
public string first { get; set; }
public string last { get; set; }
}
}
The form populates fine, I see the error if I don't put anything into first and the form won't submit. After populating something into first I get the ajax call and then it posts "Success" to the div.
However, this is the problem, the error "the first field is required." still remains on the page. It's as if the ajax submit form is going through before the validation gets a chance to clear the error, and then it never gets the chance.
Any way to get the validation to still remove the errors?
The form is not being validated, because your onblur event is short-circuiting the submission process in jquery-unobtrusive-ajax.js.
Instead, change your onblur event for both fields to the following:
$(this).parents('form:first').find(':submit')[0].click();
This will invoke the jquery.unobtrusive-ajax.js script, causing validation to occur prior to the Ajax submission to the server.
UPDATE
When I looked back at your view, I saw that you are calling #Html.ValidateFor() for your properties. This creates HTML markup outside of the div created by #Html.ValidationSummary.
Because this markup is outside of where unobtrusive validation expects it, this markup is never overwritten, and will always remain. Remove the #Html.ValidateFor() lines. If you need to have the validation messages after your initial load, call validate() on document.ready to set your validation messages.
Because I haven't found a proper solution to this problem, I've decided to simply target the validation-summary-errors div and add the class display:none; to the li elements. This hides the validation errors that have otherwise not cleared before submitting the form.
$('#form_errors').children('div.validation-summary-errors').children('ul').children('li').css('display','none')
There has to be a better solution, but I've tried everything and can't figure out why my attempts to force validation don't work.