Partial View not rendered on the same Page in asp.net mvc - c#

I want to display the details of particular record on same page, user can choose the product from the list of Product name and as soon as user clicks on the links the details of the specific product should display on the other side of the page i.e. othe div. I tried it by creating partial View and Ajax but the details are not displayed on the separate page a new blank page is opened with the name of Partialview and the records are displayed there, but i want details on the same page.ProductName are comming from database, first time the page loads it must contains the details of first record by default, that is working OK. Please try to solve this problem. Thanks
HomeController.cs
public class HomeComtroller:Controller
{
dbProductEntity Productdbentity=new dbProductEntity();
public ActionResult ProductDetails(int id)
{
var query=Productdbentity.tbl_product.First(c=>c.ProductId==id);
return PartialView("PartialView",query);
}
public ActionResult Product()
{
return View(dbentity.tbl_product.ToList());
}
PartialView.cshtml
#model MvcProject.Models.tbl_product
<label> #Model.ProductName </label>
<label> #Model.ProductDesc </label>
Product Page
#model List<MvcProject.Models.tbl_product>
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
$(div.product a").click(function(e){
var url=this.ref;
$get(url,{},function(data) {
$('#product-detail').html(data);
});
});
});
</script>
</head>
<body>
<div class="product">
<ul class="list">
#foreach(var item in Model)
{
<li><a href="#Url.Action("ProductDetail","Home",new {id=item.ProductId})">
#item.ProductName</a></li>
}
</ul>
<div class="product-detail">
#{Html.RendererPartial("PartialView",Model.FirstOrDefault());}
</div>
</div>
</body>
</html>

You should cancel the default action of the anchor by returning false from your .click event handler:
$(document).ready(function() {
$(div.product a").click(function(e) {
var url=this.ref;
$get(url,{},function(data) {
$('#product-detail').html(data);
});
});
return false; // <-- That's the important bit you were missing
});
If you do not return false from the .click handler, the browser will simply follow the linking to which your anchor is pointing stopping any javascript execution you might have started. Returning false ensures that the browser will not redirect away from the current page, leaving you the possibility to execute an AJAX request and update the current view.

I think you are missing "." after the "$" in first line in below code. And in second line, since "product-detail" is a class name so in jQuery selector use "." (not "#") before class name. Below is the corrected code:
$.get(url,{},function(data) {
$('.product-detail').html(data);
});
For more have a look at http://api.jquery.com/jQuery.get/

You have to stop the default behavior of click event on a link.
<script>
$(function(){
$("div.product a").click(function(e){
e.preventDefault();
var url=this.ref;
$('.product-detail').load(url);
});
});
</script>

Related

Render part of page on dropdown selection part 2

This is a follow on to similar question but taking suggestions into account.
Render part of page on dropdown selection
I have a chart on my main view which I would like to update partially when a dropdown selects different values.
The page renders correctly the first time, but when I select a new value in the dropdown, then I think the .submit script is failing in the script .submit() because when I put a break on window.submitAjaxForm it is never reached.
_PnlChart.cshtml
<img src="#Url.Action("CreateTraderPnlChart3")" width="600" height="600" align="middle" vspace="50" />
My mainview Index.cshtml:
<div class="w3-half">
<div id="ExportDiv">
#{ Html.RenderPartial("_PnlChart");}
</div>
#using (Ajax.BeginForm("GetEnvironment",
new RouteValueDictionary { { "Environment", "" } }, new AjaxOptions() { UpdateTargetId = "ExportDiv" }, new { id = "ajaxForm" } ))
{
#Html.DropDownList("PeriodSelection",
new SelectList((string[])Session["Periods"]),
(string)Session["Period"],
new
{ onchange = "submitAjaxForm()" })
}
</script>
<script type="text/javascript">
$('form#ajaxForm').submit(function(event) {
eval($(this).attr('onsubmit')); return false;
});
window.submitAjaxForm = function(){
$('form#ajaxForm').submit();
}
</script>
</div>
My controller:
public ActionResult PeriodSelection(string dropdownlistReturnValue) // dont know what dropdownlistReturnValue is doing?
{
Session["Period"] = dropdownlistReturnValue;
return PartialView("~/Views/Employee/_PnlChart.cshtml");
}
This line in your code,
eval($(this).attr('onsubmit')); return false;
I am not sure what you were intending to do here. But from your question, i assume you wanted to do a form submission. But that line will not submit the form. The expression $(this).attr('onsubmit') is going to return undefined as your form does not have an onsubmit attribute defined.
But you already have the form submit code in your other method (submitAjaxForm). So if you simply remove the $('form#ajaxForm').submit handler (apparently it does not do anything useful), your code will work. When you change the dropdown, it will make an ajax form submission.
But your form action is set to GetEnvironment action method. That means your ajax form submission will be to that action method. In your question you have a different action method which returns the updated chart content. It does not makes sense!
I personally prefer to write handwritten ajax calls instead of relying on the ajax action helper methods. The below is the code i would probably use (Except the dropdownlist code. read further)
<div id="ExportDiv">
#{ Html.RenderPartial("_PnlChart");}
</div>
#Html.DropDownList("PeriodSelection",
new SelectList((string[])Session["Periods"]),
(string)Session["Period"], new
{ data_charturl = Url.Action("PeriodSelection","Home")})
Now listen to the change event of the SELECT element.
$(function(){
$("#PeriodSelection").change(function(){
var v = $(this).val();
var url=$(this).data("charturl")+'?dropdownlistReturnValue='+v;
$("#ExportDiv").load(url);
});
});
You should consider using the a view model to pass the Dropdownlist data. Why not use the DropDownListFor helper method ? It looks much clean, Mixing a lot of C# code (See all the session casting and all.) makes it kind of dirty IMHO.

Form confirmation with Razor, Url.Action

I can find many different ways to add confirmation to a form submission. The issue in my case is either they submit the form anyway or they just sit there and dont do anything. Any suggestions would be appreciated. I have added events to both the form onsubmit and the button onclick, no dice. The ActionResult in this case uses HttpPostRequest to send the form data. Works great, just want to add a confirmation dialogue that works.
<script>
function SubmitConfirm(){
if (confirm("Are you sure want to submit this form?"))
return true;
else
return false;
}
<form name="Form1" method="post" action="#Url.Action("PostForm", "MyController")" id="Form1">
...
<input type="submit" value="Submit Posting" onclick="SubmitConfirm()" />
You probably want to display that dialog without reloading the page, just when your submission is successful rather than taking them to a new page or implementing some sort of conditional refresh. So you could set up your form as such...
<form name="Form1" id="Form1">
...
<input type="button" id="submit" value="Submit Posting" />
</form>
And using jQuery set up your actual submit thusly...
$(document).ready(function () {
$('#submit').click(function() { submit(); });
});
function submit() {
if (SubmitConfirm())
{
var data = $('#Form1').serialize();
$.post('MyController/PostForm', data, function(result) {
if (result === 'success') {
// just using an alert here as a placeholder
alert('Your submission has been received!');
}
});
}
}
Which means that in your controller, you'll have the following...
[HttpPost]
public ActionResult PostForm([form arguments])
{
var success = // deal with form results, return true if everything is ok
return new Content(success ? "success" : "failure");
}
To recap, you'd submit your form data, process it, and give the user feedback as to whether it was successfully processed or not without the user ever leaving the page, which also opens the door to make it easier to re-submit data if necessary and do validation, again without the user leaving the page or having to wait for the page to reload.
EDIT: Fixed typo and modified submission logic.

mvc - applying css class to div if someone click on that div without using javascript or jquery

I am working on an MVC4 Application
#{
var = mydivID;
}
<div id="mydivID"></div>
If someone click on mydiv or when it's active then add css class="active"
Like This:
Before someone click on mydiv = <div id="mydivID"></div>
After someone click on mydiv = <div id="mydivID" class="active"></div>
i don't want to use javascript or jQuery.
Please help me.... Thank You in Advance.
You can't dynamically change the contents of the DOM without JavaScript. Your only other alternative is a full new request cycle.
View
#{
var active = ViewBag.Active as bool? ?? false;
}
<a href="#Url.Action("ThisAction", "ThisController", new { divClicked = true })">
<div id="mydivID" class="#(active ? "active" : "")"></div>
</a>
Controller
public ActionResult ThisAction(bool? divClicked)
{
ViewBag.Active = divClicked.HasValue ? divClicked : false;
return View();
}
Bonus points for using a proper model instead of ViewBag, but this illustrates the idea.
If you have multiple divs and want any of them to be clickable, you could try assigning them different IDs and passing the ID of the div into the action (and then the ViewBag) instead.

Div elements on click fires for the first element only

I am listing my data in an ItemTemplate.Then inside the ItemTemplate, i have two div tags as follows:
<ItemTemplate>
<div id="contentdiv">
<h4 id="titleresult"><%# Server.HtmlEncode(Eval("Name").ToString())%></h4>
</div>
<div id="showclick" class=hideAll>
<p class="brief"><%# Server.HtmlEncode(Eval("LegalName").ToString())%></p>
<p class="brief"><%# Server.HtmlEncode(Eval("FirstName").ToString())%></p>
<p><%# Server.HtmlEncode(Eval("LastName").ToString())%></p>
</div>
</ItemTemplate>
Then i have the css to define the hideAll class so that when the page loads, the data in this div tag is hidden until the user clicks on the contentdiv link.
.hideAll { display:none }
.displayAll { display:block; top:0px}
Then finally i have the javascript part for firing the click event.
<script type="text/javascript">
function showResults(UserID) {
var contentdiv= document.getElementById('contentdiv');
var showclick = document.getElementById('showclick');
<%
long id =0;
DataAccess dataAccess = new DataAccess();
Data = dataAccess.GetCounterParty(id);
%>
var UserID = <%=dataAccess.GetCounterParty(id) %>
contentdiv.style.visibility = "visible";
$(showclick).removeClass('hideAll');
}
</script>
The UserID is the id of every element in the list. The problem is, the click affects only the first element no matter which other element i click on the list.
In html id is used to refer to one element.
If you use it multiple times the browser would default to the first element.
You should use a class selector. Something like:
$(".contentdiv").click(function(){
$(this).next().removeClass('hideAll');
});
Here is a working example. I used toggleClass though, it seems more appropriate to me.
An id is a unique identifier, you cannot have two or more things on the same page with the same identifier and expect things to work properly. Make your identifiers unique, and bind to the click event using a class selector instead.
you should use class instead of id, id are unique, which only exist in 1 page, class can exist in multple div
some idea for u
html
<div class="showclick hideAll">
script
$('.showclick').on('click', function(){
$(this).toggle(); //toggle to show or hide, can be any element u want to toggle instead of this
});

Issues with toggleclass in jquery

I have a condition , where i have to use toggle class plus delete the class of all other list in a drop down menu ,
for instance if i select any product from the list , all the other products background position should be 0,0 , also on clicking the
same selected product again the bacground position should go back to 0,0. something similar to toggle . I just cant get the both functionality work together.
any ideas on how to get it working or any other way of doing it below is the code which i have tried so far:
for toggle i used the following jquery code :
<script type="text/javascript">
$(document).ready(function() {
$('.option-list.swatch.brass label').on("click", function() {
$(this).toggleClass('not-selected selected-value');
});
});
</script>
To change the background position of all the other list labels apart from the selected ones
<script type="text/javascript">
$(document).ready(function() {
$('.option-list.swatch.brass label').on("click", function() {
$(".option-list.swatch.brass label").each(function() {
$(this).css("background-position", "0px 0px");
});
$(this).css("background-position", "0px 50px");
});
});
</script>
<ul>
#foreach (var pvaValue in attribute.Values)
{
<li>
<label for="" class="not-selected" style="background-image:url(#(pvaValue.MenuIcon));width:50px;height:49px;">#pvaValue.Name</label>
}
</li> </ul>
<style type="text/css">
label.not-selected{background-position:0px 0px;}
label.selected-value{background-position:0px 50px;}
</style>
It is occurring because of Javascript conflict. The one which is called earlier will be overridden by later click bound function..
I would say, combine the logic from both the click bounds..
$('.option-list.swatch.brass label').on("click", function() {
//FIRST LOGIC
$(this).toggleClass('not-selected selected-value');
//SECOND LOGIC
$(".option-list.swatch.brass label").each(function() {
$(this).css("background-position", "0px 0px");
});
$(this).css("background-position", "0px 50px");
});
This should solve your problem. It's okay to call both the logic in one click event function. :-)

Categories