I define the section in Index. cshtml but when I run the application then generate an error section is not defined
I create the same another project, then define the simple method in Index. cshtml then run my application but my current project popup not be displayed??
another project
_layout.cshtml
<div class="container body-content">
#RenderBody()
#RenderSection("simpelmessage")
<footer>
<p>WebApi Crud Oeperation using Entity Framework In Mvc</p>
</footer>
</div>
Index.cshtml
#section simpelmessage{
<h1>simple message</h1>
}
that is work in another project
but my current working project my popup should not be displayed??
I m performing crud operation using api
_layout.cshtml
<div class="container body-content">
#RenderBody()
#RenderSection("alertpopup")
<footer>
<p>WebApi Crud Oeperation using Entity Framework In Mvc</p>
</footer>
</div>
Index.cshtml
#section alertpopup
{
<script src="https://cdnjs.cloudflare.com/ajax/libs/AlertifyJS/1.13.1/alertify.min.js" type="text/javascript">
$(function () {
var successmessage = '#ViewBag.message'
if (successmessage != '')
{
alertify.success(successmessage);
}
});
</script>
}
HomeController.cs
public ActionResult Index()
{
IEnumerable<studentmvcmodel> stdlist;
HttpResponseMessage response = globalvariable.webapiclient.GetAsync("studlogins").Result;
stdlist = response.Content.ReadAsAsync<IEnumerable<studentmvcmodel>>().Result;
ViewBag.message = "record is inserted";
return View(stdlist);
}
public ActionResult create()
{
return View();
}
[HttpPost]
public ActionResult create(studentmvcmodel stud)
{
var username = stud.username;
var passs = stud.password;
if (username != null && passs != null)
{
HttpResponseMessage response = globalvariable.webapiclient.PostAsJsonAsync("studlogins", stud).Result;
ViewBag.message = "data inserted successfully";
return RedirectToAction("Index");
}
else
{
ViewBag.message = "please all the data fillup carefully";
return View("create");
}
}
My record should be created, but I want to popup message when submits the record?? but give the error section is not defined??
What I am trying I went to when I press the submit button, then a popup should be displayed but popup not display?
I hope my question is understood?
I m going to the browser and then ctrl+U then show the popup function.
<script src="https://cdnjs.cloudflare.com/ajax/libs/AlertifyJS/1.13.1/alertify.min.js" type="text/javascript">
$(function popup()
{
var successmessage = 'record is inserted';
if (successmessage != '')
{
//alertify.success(successmessage);
alert('record is inserted');
}
});
popup();
</script>
To avoid section is not defined error you need to call RenderSection as below.
#RenderSection("alertpopup", false)
And to make the pop up work, you have defined your javascript function but you are not calling you function anywhere. you can do this instead.
<script src="https://cdnjs.cloudflare.com/ajax/libs/AlertifyJS/1.13.1/alertify.min.js" type="text/javascript"></script>
<script>
function popup () {
var successmessage = '#ViewBag.message'
if (successmessage != '')
{
alertify.success(successmessage);
}
}
popup();
</script>
If you return View("create"), so you should render your section in Create.cshtml Or define this #RenderSection("alertpopup", false) in your Layout
Rendering sections take two parameters; a string and a boolean as such:
#RenderSection(string name, bool required)
The name parameter is name of the section to render and required indicates that the section must always be rendered. If the section may not be rendered in some views or sometime, you should set required to false like below.
#RenderSection("alertpopup", false)
I'm also not sure when you want your popup to display because it is not called in your code. If for whatever reason you'll want it to be called when your documents loads, you should change your code to this
#section alertpopup
{
<script src="https://cdnjs.cloudflare.com/ajax/libs/AlertifyJS/1.13.1/alertify.min.js" type="text/javascript">
$(doucument).ready(function () {
var successmessage = '#ViewBag.message'
if (successmessage != '')
{
alertify.success(successmessage);
}
});
</script>
}
Related
I have the following line of code which uses html helper's PagedListPager:
#Html.PagedListPager(Model.kyc_paged_list, page => Url.Action("ClientDetails", new { id = ViewBag.ID, kyc_page = page, transaction_page = Model.transaction_page, active = "kyc" }))
When clicking on the the pager the entire page reloads. But I only want the table with id="kyc-history" to refresh.
I know how to reload the table using a JavaScript function but I don't know how to call it from the PagedListPager.
Any ideas how I can call it? Let's say that the JS function is called reloadTable()
I was having the same problem and this article (done by Anders Lybecker) helped me out and now everything working!
It's very clear with steps, But make sure to make backup before starting!
Take a look:
AJAX paging for ASP.NET MVC sites
In summary you make 2 Action Results in your Controler with 2 Views 1 for your page (in my case it's Index View) the other for the List that contain the PagedListPager control (List View). And put the list View inside the Index View. And write the JQuery code for the PagedListPager in the Index View.
You can read the article for the details!
And this is my code with a little extra things I noticed to help you more:
The List View:
#model IPagedList<StudentRegSys.Models.Student>
#{
Layout = null;
}
#using PagedList.Mvc;
#using PagedList;
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400italic,400,600,700" rel="stylesheet">
#Styles.Render("~/template/css")
<div class="container">
<div class="row">
<!-- The List Code-->
<div class="pagination-control">
#Html.PagedListPager(Model, i => Url.Action("List", "Home", new { i, search = Request.QueryString["search"] }))
</div>
</div>
</div>
#Scripts.Render("~/template/js")
Note: Make sure to make Layout = null; and put the Styles Links & the Scripts manual in this View to avoid design issues.
In the Controller: (it's Home Controller in my case)
// GET: /Home/Index
public ViewResult Index()
{
return View();
}
// GET: /Home/List
public ActionResult List(int? i, string search = "")
{
try
{
var students = _context.Student.Include(s => s.Major)
.OrderBy(s => s.Name)
.Where(s => s.Name.Contains(search) || s.Major.Name.Contains(search) ||
s.Address.Contains(search) || s.Phone.Contains(search))
.ToList().ToPagedList(i ?? 1, 8);
return View(students);
}
catch (Exception)
{
return HttpNotFound();
}
}
The Index View:
#{
ViewBag.title = "Home";
}
<section id="intro">
<!-- Some Code -->
</section>
<section id="maincontent">
#Html.Action("List") <!-- to call the List view -->
</section>
<script>
$(document).ready(function () {
$(document).on("click", ".pagination-control a[href]", function () {
$.ajax({
url: $(this).attr("href"),
type: 'GET',
cache: false,
success: function (result) {
$('#maincontent').html(result);
}
});
return false;
});
});
</script>
Note: Make sure to put the html(result) in the root container of the list in my case was <section id="maincontent">.
Hope this help you out :)
I have 2 simple scripts and 2 Thymeleaf variables, I want one script to be executed if thymeleaf variable is true, then again if other variable is true - related script to be executed and so on. But I get the following result - if one variable is true and script executed then second script won't be execudet even if second variable is true. So shortly, only one of scripts is executed, but need both (in sequence, not the same time). Here is the code:
<script th:inline="javascript">
var flag = [[${invalidInput}]]; //Thymleaf variable
window.onload = function() {
if(!flag)
return;
openForm();
};
</script>
<script th:inline="javascript">
var flag = [[${exists}]];
window.onload = function() {
if(!flag)
return;
openForm();
};
</script>
<!-- MODAL -->
<div class="form-popup" id="myForm">
<form id="registration" th:action="#{/registrate}" th:object="${newUser}" method="post" class="form-container">
<h1>Registration</h1>
<div class="alert" th:if="${exists}">
User already exists! Please try again.
</div>
<div class="invalidInput" th:if="${invalidInput}">
Username or password too short.
</div>
************************************************************
<script>
function openForm() {
document.getElementById("myForm").style.display = "block";
}
#PostMapping("/registrate")
public String login (#ModelAttribute(value = "newUser") User newUser, BindingResult bindingResult, Model model) {
userValidator.validate(newUser, bindingResult);
if(usrService.isUserPresent(newUser.getUsername())){
model.addAttribute("exists",true);
return "login";
}
else if(bindingResult.hasErrors()){
model.addAttribute("invalidInput",true);
return "login";
}
I don't think you can set the window.onload variable twice... one will simply overwrite the other. You can either combine your logic like this:
<script th:inline="javascript">
var invalidInput = [[${invalidInput}]]; //Thymleaf variable
var exists = [[${exists}]];
window.onload = function() {
if(invalidInput) {
openForm();
} else if (exists) {
openForm();
}
};
</script>
Or alternatively you could use something like jQuery, which has this functionality built in for you.
https://api.jquery.com/ready/
When multiple functions are added via successive calls to this method,
they run when the DOM is ready in the order in which they are added.
I have a script in my header that is calling a web api which should populate a view model. This is below.
#using GigHub.Controllers
#using GigHub.ViewModel
#model GigHub.ViewModel.ProjectsViewModel
#{
ViewBag.Title = "Projects";
}
<head>
<script>
(function getProjects() {
$.get("/api/projects")
.done(function () {
alert("Got Projects");
})
.fail(function () {
alert("Something failed!");
});
});
</script>
</head>
I then have my html that would loop through the viewModel and set it up throughout the html, but every time it gets run, it is throwing a null reference exception to Model.ProjectList in the for each because it hasn't populated yet. I thought putting the script in the header would let it run first, but that doesn't seem to be the case.
<h2>Projects</h2>
<ul class="gigs voffset4" style="width: 600px;">
#foreach (var project in Model.ProjectList)
{
<li>
<div class="date">
<div class="month">
#project.Name
</div>
<div class="day">
#project.Key
</div>
</div>
<div class="details">
<span class="artist">
#project.Id
</span>
<span class="genre">
#project.ProjectTypeKey
</span>
</div>
</li>
}
</ul>
Here is my actual projectsController
public class ProjectsController : Controller
{
private readonly string m_Username = Properties.Settings.Default.username;
private readonly string m_Password = Properties.Settings.Default.password;
public ActionResult Index()
{
var client = new RestClient("https://example.net/rest/api/2/");
client.Authenticator = new HttpBasicAuthenticator(m_Username, m_Password);
var request = new RestRequest("project/", Method.GET);
request.RequestFormat = DataFormat.Json;
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var response = client.Execute<List<Project>>(request);
var content = response.Content; // raw content as string
if (content == null)
throw new Exception(response.ErrorMessage);
var projectArray = JsonConvert.DeserializeObject<List<Project>>(response.Content);
var viewModel = new ProjectsViewModel()
{
ProjectList = projectArray,
Heading = "Projects"
};
return View("Projects", viewModel);
}
}
You are trying to mix javascript and C# code together and expecting it to work! No. It does not work that way.
The c# code in your view ( the foreach block) gets executed by razor in the server and the resulted html markup will be send to the client browser. That means, if you are accessing Model.ProjectList in your view, you should make sure that you are passing a model to your view with that property(ProjectList).
You have 2 options.
1. Full server side approach
In your get action, create an object of your view model, set the ProjectList property and send it to view.
public ActionResult Index()
{
var vm = new YourViewModel();
vm.ProjectList= GetListOfProjectsFromSomeWhere();
return View(vm);
}
private List<ProjectItem> GetListOfProjectsFromSomeWhere()
{
var list=new List<ProjectItem>();
list.Add(new ProjectItem { Name="Project 1"}); // Replace with real data here
return list;
}
Assuming you have a view model called YourViewModel as below
public class ProjectItem
{
public string Name {set;get;}
}
public class YourViewModel
{
public List<ProjectItem> ProjectList {set;get;}
}
and
and make sure your razor view is strongly typed to this view model
#model YourViewModel
<h2>Projects</h2>
#foreach (var project in Model.ProjectList)
{
<p>#project.Name</p>
}
2. Use ajax to load page content.
From your client side code,make the call to your api(like you did) and parse the response and update the DOM.
You need to create a container element in your view so that your javascript code can append items to that from the api call result.
<ul id="projects"></ul>
Now make sure that your javscript code will execute on the document ready event.
function getProjects() {
$.get("/api/projects")
.done(function (data) {
var projectHtml="";
$.each(data,function(i,item){
projectHtml+="<li>"+item.Name+"-"+item.Key+"</li>";
});
$("#projects").html(projectHtml);
})
.fail(function () {
alert("Something failed!");
});
}
$(function(){
getProjects();
});
Assuming your api call returns an array of item, each with a Name & Key property like this
[{Name:"Project1", Key:"Pr1"},{Name:"Project2", Key:"Pr2"}]
I am trying to call a js function inside my view :
#model DomainClass.Group
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
<script language="javascript" type="text/javascript">
document.read = function myFunction() {
if (ViewBag.State == "error") {
if (confirm("معیار مورد نظر دارای زیر مجموعه های مرتبط است. آیا تمایل به ویرایش دارید ؟")) { } else {
history.back();
}
}
}
</script>
}
}
#using (Html.BeginForm())
{
//my code
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
As you can see the my function name is myfunction and it depends on viewbag value ,but never it is't called by browser!!!
Should i add extra code to my view ?
Any ideas will be appreciated .
Best regards
Your Script is never executed because it won't be rendered to the page. So i moved it out of the server tags and into the HTML markup. Only filling in the parameter you need. But then you have a second problem. You sign the function to a variable on the window. No matter the name of the function on the right side it will be named the one on the left side. In fact, the right side shouldn't have a name al togheter. Then the third and final problem is, you don't call the function anywhere. Since i see that you included jquery validate i presume you also included jQuery and made use of their document ready function.
I've included an update of your function. There is some more room for optimalisation but it didn't include them to make it clear where your mistakes where.
#model DomainClass.Group
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script language="javascript" type="text/javascript">
//use window instead of document
window.myFunction = function () {
//Try setting the boolean this way
var x = #(ViewBag.State == "error" ? "true" : "false");
if (confirm("معیار مورد نظر دارای زیر مجموعه های مرتبط است. آیا تمایل به ویرایش دارید ؟")) {
}
else {
history.back();
}
}
$(function () {
window.myFunction();
});
</script>
#using (Html.BeginForm())
{
//my code
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
I'm using MVC 4 and Entity Framework to develop an intranet web app. On one of my views, I have to implement the autocomplete feature. To do that, I'm using Bootstrap Typeahead. I tried to pass my action (so my function) to feed the input element but it seems that it doesn't work.
Here is my action result which returns an Json :
public ActionResult AutoComplete(string term)
{
var result = db.Persons.Where(p => p.FirstName.ToLower().Contains(term.ToLower()) || p.LastName.ToLower().Contains(term.ToLower())).ToList().Select(p => p.FullName).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
My View and my script :
#model IEnumerable<BuSIMaterial.Models.Person>
#{
ViewBag.Title = "Index";
}
<link href="/Content/PagedList.css" rel="stylesheet" type="text/css" />
<h2>Index</h2>
<input type="text" class="typeahead" data-provide="typeahead">
#section Scripts
{
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jqueryui")
#Styles.Render("~/Content/themes/base/css")
$(".typeahead").typeahead({
source: function (query, process) {
var persons = [];
map = {};
// This is going to make an HTTP post request to the controller
return $.post('/Person/AutoComplete', { query: query }, function (data) {
// Loop through and push to the array
$.each(data, function (i, person) {
map[person.Name] = person;
map[person.F]
persons.push(country.Name);
});
// Process the details
process(countries);
});
},
updater: function (item) {
var selectedShortCode = map[item].ShortCode;
// Set the text to our selected id
$("#details").text("Selected : " + selectedShortCode);
return item;
}
});
</script>
}
In my master page, I call the Bootstrap jquery file(s). Any idea about what's going on?