I am working on asp.net MVC 2 application. I have ajax.action link but it is not working. I have this code in my view:
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
<script type="text/javascript">
function success(result) {
alert(result);
// TODO: do something with the object
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<%: Ajax.ActionLink(
"Delete",
"Delete",
new { Id = 55 },
new AjaxOptions { OnComplete = "success" })
%>
</asp:Content>
and this is controller code:
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
public JsonResult Delete(Int32 Id) {
return Json("Record deleted!", JsonRequestBehavior.AllowGet);
}
But when I click the link, It shows Record deleted! in browser instead of showing as alert. Am I missing some file(s) ?
You might need to include the MicrosoftAjax.js and MicrosoftMvcAjax.js scripts to your page:
<script type="text/javascript" src="<%= Url.Content("~/scripts/MicrosoftAjax.js") %>"></script>
<script type="text/javascript" src="<%= Url.Content("~/scripts/MicrosoftMvcAjax.js") %>"></script>
In ASP.NET MVC 3 and later those files are obsolete and replaced by the jQuery unobtrusive scripts.
Now that you have sent me your sample project by mail it is clear what the problem is. You have defined your success javascript function inside the <title> tag of your page which obviously cannot work.
So inside your MasterPage you should define a special placeholder for your scripts (notice also how I have fixed your hardcoded links to the CSS file with a url helper):
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
<link href="<%= Url.Content("~/Content/Site.css") %>" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<%= Url.Content("~/scripts/MicrosoftAjax.js") %>"></script>
<script type="text/javascript" src="<%= Url.Content("~/scripts/MicrosoftMvcAjax.js") %>"></script>
<asp:ContentPlaceHolder ID="Scripts" runat="server" />
</head>
that you could override in your view:
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="Scripts" runat="server">
<script type="text/javascript">
function success() {
alert('success');
// TODO: do something with the object
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<%= Ajax.ActionLink(
"Delete",
"Delete",
new { id = 55 },
new AjaxOptions { OnComplete = "success" }
) %>
</asp:Content>
Related
iam working on fileUpload in mvc.
my code is as follows:
Views/Client/AddClient.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Auditz.UI.Web.Automation.ClientService.ClientDto>" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h1>
Add A Client</h1>
<% using (Html.BeginForm("AddClient","Client",FormMethod.Post,new {enctype = "multipart/form-data" }))
{ %>
<%: Html.ValidationSummary(true) %>
<div class="tabcontrol">
<asp:Panel ID="pnlClientDtls" runat="server">
<asp:TabContainer ID="TabContainer" runat="server" Width="100%" ActiveTabIndex="1">
<asp:TabPanel ID="tb1" runat="server">
<HeaderTemplate>
Client Details
</HeaderTemplate>
<ContentTemplate>
<div class="formelements">
.....................
..............
</div>
Controllers/FileUploadController.cs
namespace FileUploadTest.Controllers
{
public class FileUploadController : Controller
{
//
// GET: /FileUpload/
public ActionResult FileUpload()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FileUpload(HttpPostedFileBase uploadFile)
{
if (uploadFile.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("~/Uploads"),
Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
}
return View();
}
}
}
Evrything works as desired with this code.
But if i place and in of Shared/Site.Master,iam getting null value in "HttpPostedFileBase uploadFile".
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
</form>
<div>
<asp:ContentPlaceHolder ID="MainContent" runat="server">
</asp:ContentPlaceHolder>
</div>
i cannot remove from my code as i want to add few ajax controls.
Make sure that you don't nest HTML forms. So in your Master page when you open the <form> tag ensure that you close it before rendering the view:
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
</form>
...
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
</body>
I can't see why the following form performs a full postback instead of asynchronously using AJAX. Request.IsAjaxRequest() is always false. I think I've followed all the examples correctly. What am I doing wrong?
Here's the view:
#(Layout = null)
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.4.4.js" type="text/javascript"></script>
</head>
<body>
<div>
<div id="update"></div>
#using(Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "update" }))
{
<input type="submit" value="test" />
}
</div>
</body>
</html>
And here's the controller:
using System.Web.Mvc;
namespace TheHoges.Web.Controllers
{
public class TestController : Controller
{
public ActionResult Index()
{
if (Request.IsAjaxRequest())
{
// never gets here
return Content("it worked");
}
return View();
}
}
}
For reference:
AJAX and MVC 3
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
Do you see this in you web.config?
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
If, yes, including the library above should solve your problem.
Just to be thorough I created a test page. Works peachy...
#{
ViewBag.Title = "Home Page";
}
#(Layout = null)
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
</head>
<body>
<div>
<div id="update">
</div>
#using(Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "update" }))
{
<input type="submit" value="test" />
}
</div>
</body>
</html>
I am having the following
<form action="<%=Url.Action("PasswordDetails",new{Controller = "User"}) %>" method="post" name="PasswordForm" id="PasswordForm" enctype="multipart/form-data">
However, the $("#PasswordForm").submit(function() {
if (validate())
return true;
else
return false;
}); isn`t being passed through.
What is wrong?
<% using (Html.BeginForm("PasswordDetails", "User", FormMethod.Post, new { id = "PasswordForm" }))
{ %>
Your view page should look like this:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm("PasswordDetails", "User",
FormMethod.Post, new { id = "PasswordForm" }))
{ %>
<input type="password" id="sitepassword" />
<input type="submit" value="Submit" />
<% } %>
</asp:Content>
and your site master like this:
<body>
<div class="page">
<div id="main">
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
<div id="footer">
</div>
</div>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type='text/javascript'>
function validate() {
alert('hello');
}
$(document).ready(function () {
$("#PasswordForm").submit(function () {
if (validate()) return true;
else return false; });
});
</script>
</body>
I am trying to use jQuery ajax with MVC I can get it to post back to the action I want and it returns the ViewData objects with updated Data but never renders the HTML. I have a View which contains some MVC User Controls and I want them to update on a timer.
Here is my View Markup
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/PageWithSummaryViewAndTabs.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="FullCaseTitle" ContentPlaceHolderID="TitleContent" runat="server">
</asp:Content>
<asp:Content ID="FullCaseContent" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
window.setInterval(test, 5000);
function test() {
jQuery.get("/PatientCase/RefreshEPRF", function(response) { });
}
</script>
<div id="loadingDiv" style="display:none">Updating</div>
<input id="refreshPatientCaseIndexButton" type="submit" visible="true" title="refresh" value="Refresh" />
<h2>Full Case</h2>
<div id="EPRFContent">
<%Html.RenderPartial(#"~/Views/PatientCase/SectionEPRF.ascx"); %>
<%Html.RenderPartial(#"~/Views/PatientCase/SectionDrugs.ascx"); %>
</div>
<div id="ImageContent">
<%Html.RenderPartial(#"~/Views/PatientCase/SectionImagery.ascx"); %>
</div>
</asp:Content>
On postback i call a Action Called RefreshEPRF which loads just the required user controls again
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%Html.RenderPartial(#"~/Views/PatientCase/SectionEPRF.ascx"); %>
<%Html.RenderPartial(#"~/Views/PatientCase/SectionDrugs.ascx"); %>
And finaly the marpup in the control
<table id="detailstable">
<tr><td id="detailslablecolumn">Patient Name : </td><td>
<%
foreach (var item in (List<STS_Lite.Models.PatinetCase.EPRFItem>)ViewData["EPRF"])
{
if (item.datumItemId == 46)
{
if (item.Stroke)
{
%>
<img src="/PatientCaseIndex/InkImageData/GetInkImage/<%=ViewData["PatientCaseId"]%>/<%=ViewData["TemplateInstanceId"]%>/<%=item.TemplateItemId %>" />
<%
}
else
{%>
<%=item.Value.ToString()%>
<%}
break;
}
}
%></td></tr><table>
When I step through this code the ViewData in the user control has the new updated values but the page comes back with no new values. I have tried the jQuery.get and ajax but with no luck.
Any help would be great thanks
You have to write your response... try doing this :
jQuery.get("/PatientCase/RefreshEPRF", function(response) {
$("#EPRFContent").html(response) });
The response parameter should contain your view, and doing this simply put its content into your div.
your action Called RefreshEPRF should however return a partial view
I'm working with some nested datalist controls and cannot get the SP parameters for my nested stored procedure to work.
In debug I can see that SqlDataSource2.SelectParameters.Add("Section",oLabel.Text.ToString()); is getting the correct value from the label but when the results display I always get the results for the last parameter added?
I'm guessing I need to clear the parameters in some way each time the nested datalist is bound but if I add code to do that it results in an error that I have not specified the parameters?
My code is below, you'll see that eventually I will have 3 nested datalists inside each other - or that's the plan.
Thanks for any suggestions
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="nhscsharprepeater._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%# Import Namespace="System.Web" %>
<%# Import Namespace="System.Web.UI" %>
<%# Import Namespace="System.Data" %>
<script type="text/C#" runat="server">
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
DataList oList = (DataList)e.Item.FindControl("Datalist2");
Label oLabel = (Label)e.Item.FindControl("lblSection");
DataList oList2 = (DataList)oList.FindControl("Datalist3");
SqlDataSource2.SelectParameters.Clear();
SqlDataSource2.SelectCommand = "report_DistinctSubSections";
SqlDataSource2.SelectParameters.Add("Section",oLabel.Text.ToString());
oList.DataBind();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:productfolioConnectionString %>"
SelectCommand="report_DistinctSection" SelectCommandType="StoredProcedure"></asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:productfolioConnectionString %>"
SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter Name="Section" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:productfolioConnectionString %>"
SelectCommand="report_getReports" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter Name="SubSection" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1" RepeatColumns="2" RepeatDirection="Horizontal" OnItemDataBound="DataList1_ItemDataBound">
<ItemTemplate>
<asp:Label Runat="server" text='<%# DataBinder.Eval(Container.DataItem, "Section") %>' ID="lblSection">
</asp:Label>
<br />
<asp:datalist id="Datalist2" runat="server" DataSourceID="SqlDataSource2">
<ItemTemplate>
<asp:Label Runat="server" text='<%# DataBinder.Eval(Container.DataItem, "SubSection") %>' ID="lblSection">
</asp:Label>
<br />
<asp:datalist id="Datalist3" runat="server" DataSourceID="SqlDataSource3">
<ItemTemplate>
<!--<asp:Label Runat="server" text='<%# DataBinder.Eval(Container.DataItem, "Report") %>' ID="lblSection">
</asp:Label>-->
</ItemTemplate>
</asp:datalist>
</ItemTemplate>
</asp:datalist>
</ItemTemplate>
</asp:DataList>
</div>
</form>
</body>
</html>
One might guess that calling Clear on SqlDataSource2.SelectParameters before calling Add might do the trick.