I've a menu list displayed in the browser as a list of anchor tags. When a user clicks I'm passing its id to controller using ajax as following:
<!DOCTYPE html>
<script type="text/javascript">
$(document).on('click', 'a', function () {
var Url = $(this).attr("href");
$.ajax({
type: 'POST',
url:Url,
contentType: 'application/json; charset:utf-8',
data: JSON.stringify({ id: this.id })
})
});
</script>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<link href="/Content/bootstrap.css" rel="stylesheet">
<title>ShopOnline</title>
</head>
<body>
<div id="soContainer">
<div id="soCategories">
<div class="container">
<ul class="list-inline">
<li>
Everything
<ul id="catUL">
#foreach (var c in Model.CategoriesWithCount)
{
<li>
<a id="#c.Key" href ="#Url.Action("ListOfBrandNames","Home")">#c.Key</a>
(#c.Value)
</li>
}
</ul>
</li>
</ul>
<ul class="list-inline" id="topMenu">
<li>Bought Before</li>
<li>Specials</li>
</ul>
</div>
</div>
</div>
</body>
</html>
Now this id is passed down to the following action method as parameter to get a list of string(i.e., brand names) to send to a View as:
[HttpPost]
public ActionResult ListOfBrandNames(string id)
{
var result = db.Items.Where(x => x.Category.Name.Equals(id)).Select(x => x.BrandID).ToList();
var ListOfBrands = db.Brands.Where(t => result.Contains(t.BrandID)).ToList();
var brandNanes = ListOfBrands.Select(f => f.Name.ToString()).ToList();
return View(brandNanes);
}
Above code successfully passes desired list of string to following View as:
#model List<string>
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>ListOfBrandNames</title>
</head>
<body>
<table>
<tr>
#foreach (var i in Model)
{
<td>
#i.ToString();
</td>
}
</tr>
</table>
</body>
</html>
for loop in View successfully runs for all elements in the list but program is breaking with a 404 Error in the browser when the list ends in the for loop. Am I calling the View incorrectly or something?
You're making two separate requests when you click on a link. First is your AJAX request, which is succeeding. But, since you're clicking on a link, you're also making a standard GET request when your browser tries to follow that link. This second request is failing, because GET is not allowed on that controller action.
You could cancel the default request in your JavaScript code:
$(document).on('click', 'a', function (e) {
e.preventDefault();
// the rest of your code...
});
Or you could maintain your current pattern of using # in your links and store the URL in something other than href. Something like:
<a id="#c.Key" href="#" data-href="#Url.Action("ListOfBrandNames","Home")">#c.Key</a>
and in your JavaScript:
var Url = $(this).data("href");
Or perhaps replace the link entirely with a button (which would be more semantically correct I suspect):
<button type="button" id="#c.Key" data-href="#Url.Action("ListOfBrandNames","Home")">#c.Key</button>
That way it wouldn't have a default action (be aware of any <form> tags involved as well of course) but would just be used to invoke a client-side operation, which is what you're doing in the code anyway.
Either way is up to you, but the main point is that you need to prevent the browser from making the GET request to your POST-only action.
it looks like you are using an a tag to do what you should be doing with a button tag.
you can just use a button tag instead of an a tag, you may have to use some css to make it look like an a tag
2.you dont have to put the URL in the href property of the a tag if you dont actually want to you use it like a regular a tag.
for example you can place it in the data-href attribute
<a id="#c.Key" data-href ="#Url.Action("ListOfBrandNames","Home")">#c.Key</a>
...
var Url = $(this).attr("data-href");
this will prevent the a tag from trying to navigate to that url when you click on it.
note that this may course the cursor icon to change, you can fix that by setting href="#" or style="cursor:pointer"
Related
I have a partial view which renders a visual form made entirely in HTML with some .css. What I want to do is reuse this same form in the same page [n] number of times. In my HomeController class I am instantiating the model as such:
public IActionResult Index()
{
List<Foo> foos = new List<Foo>();
foos.Add(new Foo { Name = "John" });
foos.Add(new Foo { Name = "Dave" });
foos.Add(new Foo { Name = "Sean" });
foos.Add(new Foo { Name = "Alan" });
return View(foos);
}
Then in my index.cshtml I am iterating using the list I receive from my controller and generating a partial view based on the length of my list
#model List<HelloWorld.Models.Foo>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Foo</title>
<link rel="stylesheet" href="~/foo/styles.css" />
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="~/foo/FooActions.js"></script>
</head>
<body>
#{
foreach (Foo foo in Model)
{
ViewData["Name"] = foo.Name;
<partial name="_Foo" view-data="ViewData" />
}
}
</body>
</html>
This is how I have my partial view set up:
<script type="text/javascript">
init('#ViewBag.Name');
</script>
<div class="foo-background">
<section>
<div>
<span class="score-text" id="redText">0</span>
</div>
<div class="green-bar"></div>
<div class="red-bar"></div>
<div>
<span class="bonus-score-text" id="greenText">0</span>
</div>
</section>
<section>
<div class="alphanumeric-display">
<p class="alphanumeric-display-text" id="textLine1">Text</p>
<p class="alphanumeric-display-text" id="textLine2">Text</p>
<p class="alphanumeric-display-text" id="textLine3">Text</p>
</div>
<div>
<span class="person-grade-text" id="goldText">0</span>
</div>
</section>
</div>
This form pulls data from a local database and displays data based on the person its tied to. The data shows up fine if its only displaying data of one person in the page. I'm using JavaScript to grab either the class or the id of these html elements and update their respective data.
But now what its doing is showing all the forms side-by-side, only, the data is wrong. None of the forms show the data from the table as they appear in the database. Upon closer inspection looks like it has a problem where each of these forms cant have the same class or ids. I'm getting this in error in all places where I have class or id elements
id attribute value must be unique: Document has multiple static
elements with the same id attribute: textLine1
Its the same error for each of my html elements.
Can someone help me understand what I am doing wrong? What can I do in order to get this to work properly?
I go to a View, submit data via POST, but the redirect cannot find the Controller method. What am I doing wrong here? After submitting the form I get:
404 error: cannot find page. URL is: http://localhost:52008/InternalController/UpdateCardFormPost
Snippet from InternalController.cs:
public ActionResult UpdateCardFormView()
{
var CardToUpdate = new CardView();
return View(CardToUpdate);//return implementation of Cards.cshtml with the empty model that was passed to it
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UpdateCardFormPost(CardView c)
{
CardModelIO.WriteCard(c);//#TODO: IMPLEMENT
return View("CardDetailView", c);
}
UpdateCardFormView.cshtml (the view with the form I am submitting):
#using LeanKit.API.Client.Library.TransferObjects
#model CardView
<!DOCTYPE html>
<html>
<!--Form used to change a card
STARTING DISPLAY called by in Internal/UpdateCardFormView
ENDING DISPLAY (post) called by UpdateCardForm in InternalController a specified below-->
<head>
</head>
<body>
#Html.BeginForm("UpdateCardFormPost", "InternalController", FormMethod.Post)
#Html.TextBoxFor(c => c.AssignedUserName);
<input type="submit" value="Submit Changes" />
</body>
</html>
Heres the CardDetailView.cshtml (the view I should be redirected to):
#using LeanKit.API.Client.Library.TransferObjects
#model IEnumerable<CardView>
<!--used for displaying an individual card in detail view
referenced in UpdateCardFormPost() method of Internal controller-->
<!DOCTYPE html>
<html>
<head>
</head>
<body>
CardView j = Model;
<p>j.AssignedUserId</p>
</body>
</html>
You've specified the controller name as InternalController but it's probably just called "Internal".
Try changing
#Html.BeginForm("UpdateCardFormPost", "InternalController", FormMethod.Post)
to
#Html.BeginForm("UpdateCardFormPost", "Internal", FormMethod.Post)
you are missing closing form tag
you should do it like
using (#Html.BeginForm("UpdateCardFormPost", "InternalController", FormMethod.Post))
{
...
}
#using(Html.BeginForm())
{
#Html.TextBoxFor(c => c.AssignedUserName);
<input type="submit" value="Submit Changes" />
}
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";
});
My requirement is like I need to display the partial view in dynamic div based on the user presses the Add another button. I tried the below code but I can't achieve it.
<html>
<head>
<title>Index</title>
<script type="text/javascript" src="../../Scripts/jquery-1.5.1.min.js"></script>
<script type="text/javascript" src="../../Scripts/jquery-ui-1.8.11.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var i = 0;
$("#chkAccecpt, #btnAccept").click(function () {
i++;
var divElement = "<br /><div id='container"+i+"'"+"> </div>";
$("#frmAccept").append(divElement);
$("#container1").load('#Url.Content("../../Views/Shared/UserInfoPartialView.cshtml")');
});
});
</script>
</head>
<body>
<div id="MainContent">
<form id="frmAccept" method="post" action="#">
<input type="checkbox" id="chkAccecpt" value="1" /> AddAnother
<br />
<input type="button" id="btnAccept" value="Add Another" />
<br />
<div id="userDetailsInfoContainer" class="Container">
#Html.Partial("~/Views/Shared/UserInfoPartialView.cshtml")
</div>
// Here I need the dynamic container1 div with that partial view controls also
</form>
</div>
</body>
</html>
I would consider fetching the partial view using Ajax
$.get("/urlToPartialViewAction",function(data){
$("#container1").html(data);
});
This will put in the view for you and insert it into a container of your choosing.
Just make sure the action returns a PartialView
Why are you calling from server
just clone container
$('#container').clone().attr("id","container1").appendTo('#frmAccept');
and you can't access view directly from browser , you have to add action for it.
You can easily do this using JQuery's Ajax method. It also allows for parameter to be send to the action.
$.ajax({
url: "#Url.Action("YourActionName", "YourControllerName")",
//data: {param1: value1, param2: value2} //add your parameters here
success: function (data) {$("#container1").html(data)},
error: $("#container1").html("")
)}
I need to insert some JavaScript code inside a UserControl that I load from an Ajax call via jQuery Ui Tabs. Let me explain...
This is my View (with jQuery loaded)
<script type="text/javascript">
$(document).ready(function () {
$("#tabs").tabs({
cache: false,
});
getContentTab (1);
});
function getContentTab(index) {
var url='<%= Url.Content("~/Home/getUserControl") %>/' + index;
var targetDiv = "#tabs-" + index;
$.get(url,null, function(result) {
$(targetDiv).html(result);
});
}
</script>
<div id="tabs">
<ul>
<li>Nunc tincidunt</li>
<li>Proin dolor</li>
<li>Aenean lacinia</li>
</ul>
<div id="tabs-1">
</div>
<div id="tabs-2">
</div>
<div id="tabs-3">
</div>
</div>
With these lines of code I call the Ajax function to load the content into a DIV.
This is the Action from the controller:
public ActionResult getUserControl(int num)
{
return PartialView("TestUC", num);
}
And this is the UserControl...
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
Number... <span id="testSpan"><%=Model.ToString() %></span>!!
<input type="button" value="Click me!!" onclick="message();" />
<script type="text/javascript">
function message(item) {
alert($("#testSpan").html());
}
</script>
The problem is that the message() function returns always 1 (instead of returning the correct number).
My question is... How should I add the script to my UserControl in order to have my code running correctly?
I'm just guessing here.
I guess your problem is that when a tab is loaded, it stays in the DOM even if you open another one (i.e. If the #1 is the default, it will remain loaded even if you click on the second one).
If this is happening, when you call the message function, there will be multiple elements with the id "testSpan", and the jQuery selector $("#testSpan") will return the first of them.
I suppose this is just some test code, but for this particular case I would go with adding the <%= Model.ToString() %> as an argument to the javascript function.
Again, I'm just guessing about the behavior of the jquery-ui tabs() function.
Regards
Try Adding script like this
<script type="text/javascript" defer="defer">
function message(item) {
alert($("#testSpan").html());
}
</script>