How to duplicate or repeat the partial view using jquery - c#

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("")
)}

Related

ASP.NET-MVC not rendering View

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"

How to use angularJs for dynamically created HTML(Which is not loaded to DOM)

Hello I am very new to AngularJs.
I am retrieving the HTML data from C# by calling ajax function. Here i am trying to use the AngularJs functionality for the dynamically generated HTML. But i am not able to see any AngularJs effect on this.But AngularJs effect is working fine for static HTML.Please help me on this.
Below is the example.
C# Code:
[WebMethod]
public static string DynamicHtml()
{
StringBuilder sb=new StringBuilder();
sb.append("
<div ng-app='myApp' ng-controller='myCtrl'>
<h1 id='myName' ng-click='changeName()'>
{{firstname}}
</h1>
</div>
");
return sb.ToString();
}
HTML Code: myPage.aspx
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
</head>
<body>
<div id="div1">
</div>
</body>
</html>
Script
$(document).ready({
$.ajax({
type:'POST',
content-type:'application/json;charset-4',
url:'myPage.aspx/DynamicHtml'
success:function(data){
$("#div1").html(data.d);
ChangeNameFunc();
}
})
function ChangeNameFunc()
{
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.firstname = "John";
$scope.changeName = function () {
$scope.firstname = "Nelly";
}
});
}
});
In the above code i am retrieving the html data from c# by using ajax call and binding it to div1. When i try to click on John the name is not changing to Nelly. Please note that Angular function worked when used in static page.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
</head>
<body ng-app='myApp' ng-controller='myCtrl'>
<div id="div1">
</div>
</body>
</html>
Please try declaring the ng-app and ng-controller in the itself and let me know.

How to redirect to another page and specific div on button click in mvc

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";
});

JQWidgets not working in MVC 4

I am trying to use the sample off of jqWidgets for the ListBox. I have copied the code directly into my index.cshtml file. I am not seeing the desired results, which would be what the sample looks like. All it is showing me is the button.
Here is a link to the page. I have reduced the content and allowed for anyone to look at it: https://drive.azurewebsites.net/Question
Here is the sample's website: http://www.jqwidgets.com/jquery-widgets-documentation/documentation/jqxlistbox/jquery-listbox-getting-started.htm
I'm not sure how to troubleshoot this or where to look to see what is really going wrong. I am using Chrome and pulled up Inspect Element. The scripts are being retrieved.
Here is my code:
<link rel="stylesheet" href="~/Scripts/jqwidgets/styles/jqx.base.css" type="text/css" />
<script type="text/javascript" src="~/Scripts/jqwidgets/jqxcore.js"></script><script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="~/Scripts/jqwidgets/jqxbuttons.js"></script>
<script type="text/javascript" src="~/Scripts/jqwidgets/jqxscrollbar.js"></script>
<script type="text/javascript" src="~/Scripts/jqwidgets/jqxlistbox.js"></script>
<body>
<div id='content'>
<script type="text/javascript">
$(document).ready(function () {
var source = [
"Affogato",
"Americano",
"Bicerin",
"Breve",
"Café Bombón",
"Café au lait",
"Caffé Corretto",
"Café Crema",
"Caffé Latte",
];
// Create a jqxListBox
$("#jqxlistbox").jqxListBox({ source: source, width: '200px', height: '200px' });
// disable the sixth item.
$("#jqxlistbox").jqxListBox('disableAt', 5);
// bind to 'select' event.
$('#jqxlistbox').bind('select', function (event) {
var args = event.args;
var item = $('#jqxlistbox').jqxListBox('getItem', args.index);
$("#eventlog").html('Selected: ' + item.label);
});
$("#button").jqxButton();
$("#button").click(function () {
var item = $('#jqxlistbox').jqxListBox('getSelectedItem');
if (item != null) {
alert(item.label);
}
});
});
</script>
<div id='jqxlistbox'>
</div>
<div style="margin-top: 10px;">
<input id="button" type="button" value="Get Selected Item" />
<div id="eventlog"></div>
</div>
</div>
</body>
Your Scripts are not referenced correctly. In MVC4, the process of referencing Scripts is different - http://www.jqwidgets.com/jquery-widgets-documentation/documentation/asp.net-integration/asp.net-binding-to-sql-database-mvc4.htm

Dialog Box appears and then disappears

When I click on the button Dialog Box it appears and disappears, I tired using different plugins and hundreds of tutorial but dunno why things not working properly maybe because, I am using ASP.Net page and its inheriting from a masterpage
here's the code,
<asp:Content ID="Content4" ContentPlaceHolderID="cphSubmit" runat="server">
<div id="question" style="display:none; cursor: default">
<h1>Would you like to contine?.</h1>
<input type="button" id="yes" value="Yes" />
<input type="button" id="no" value="No" />
</div>
<input id="test" type="submit" value="Show Dialog" />
<script type="text/javascript" src="/_layouts/1033/jquery.js"></script>
<script type="text/javascript" src="/_layouts/1033/ui.core.js"></script>
<script type="text/javascript" src="/_layouts/1033/jquery-ui-1.7.3.custom.js
"></script>
<script type="text/javascript" src="JS.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#test').click(function() {
$.blockUI({ message: $('#question'), css: { width: '275px' } });
});
$('#yes').click(function() {
// update the block message
$.blockUI({ message: "<h1>Remote call in progress...</h1>" });
$.ajax({
url: 'wait.php',
cache: false,
complete: function() {
// unblock when remote call returns
$.unblockUI();
}
});
});
$('#no').click(function() {
$.unblockUI();
return false;
});
});
</script>
<hr />
</asp:Content>
Its a jquery plugin I downloaded from here,
Jquery Plugin I am using
because you are using
<input id="test" type="submit" value="Show Dialog" />
which cause postback due to which dialog disappear try
<input id="test" type="button" value="Show Dialog" />
your button #test is a submit button, that needs to prevent submitting to form if you want to see the message
try
$('#test').click(function(e) {
e.preventDefault();
$.blockUI({ message: $('#question'), css: { width: '275px' } });
});
Try this code, I hope it will work:
$('#your form name').submit(function() {
$.blockUI({ message: $('#question'), css: { width: '275px' } });
});

Categories

Resources