Asp.net MVC jquery-ajax don't render html - asp.net-mvc

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

Related

ajax.action link is not showing alert on success

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>

issue with fileUpload in MVC if site.master contains <scriptmanager>

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>

ASP.NET MVC IDENTITY_INSERT is set to OFF

I have the following code in my HomeController:
public ActionResult Create()
{
return View();
}
[ValidateInput(false)]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude = "Id")]Article articleToCreate)
{
if (!ModelState.IsValid)
return View();
try
{
_db.AddToArticleSet(articleToCreate);
articleToCreate.posted = DateTime.Now;
_db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
And this is the view for the Create Method
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Create
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div id="create">
<h2>Create News Article <span>( <%=Html.ActionLink("Cancel", "Index") %> )</span></h2>
<% using (Html.BeginForm()) {%>
<fieldset>
<legend>Fields</legend>
<p>
<label for="headline">Headline</label>
<%= Html.TextBox("headline") %>
</p>
<p>
<label for="story">Story <span>( HTML Allowed )</span></label>
<%= Html.TextArea("story") %>
</p>
<p>
<label for="image">Image URL</label>
<%= Html.TextBox("image") %>
</p>
<p>
<input type="submit" value="Post" />
</p>
</fieldset>
<% } %>
</div>
<!-- END div#create -->
</asp:Content>
The problem I get when I try and submit the data is an InnerException saying that the IDENTITY_INSERT is set to off. However the ID in my article table (which is called storyId) is set to Auto Increment, and is also set as Identity and also as primary key/index.
How do I fix this problem? Thanks.
Did you create the Linq To SQL DBML file and then change the Database Schema to all for Auto Increment? I'm thinking that you may have changed the schema but forgot to update the linq designer.
Just delete the table in the designer and re-drag it from the database.

ASP.NET MVC and tinyMCE

I'm getting some very strange behaviour with tinyMCE in an ASP.NET MVC 2 beta app (same happend with MVC 1). I have a view called "edit.aspx" that is called when the user tries to create or edit an entity. The view uses jquery to load tinyMCE where ever it finds textarea's.
Here are my 2 action methods that both call the same "edit.aspx" view
public ActionResult Create()
{
return View("Edit", new FutureEvent());
}
[HttpGet]
public ActionResult Edit(int id)
{
FutureEvent futureEvent = (from fe in adminGalleryRepository.FutureEvents
where fe.ID == id
select fe).FirstOrDefault();
return View("Edit", futureEvent);
}
The "Edit.aspx" view:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Admin.Master" Inherits="System.Web.Mvc.ViewPage<DomainModel.Entities.FutureEvent>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Future event
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
$(function() {
$("#tabs").tabs();
$('textarea').tinymce({
script_url: '../../Scripts/tiny_mce/tiny_mce.js',
theme: "advanced",
plugins: "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
// Theme options
theme_advanced_buttons1: "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
theme_advanced_buttons2: "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
theme_advanced_buttons3: "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
theme_advanced_buttons4: "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
theme_advanced_toolbar_location: "top",
theme_advanced_toolbar_align: "left",
theme_advanced_statusbar_location: "bottom",
theme_advanced_resizing: true
});
});
</script>
<h2>Future event</h2>
<%= Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.") %>
<% using (Html.BeginForm("Edit", "FutureEvents")) {%>
<div id="tabs">
<ul>
<li>Future event</li>
</ul>
<div id="tabs-1">
<%= Html.Hidden("ID") %>
<label class="formLabel" for="Title">Title:
<%= Html.ValidationMessage("Title", "*") %>
<%= Html.TextBox("Title", Model.Title, new { size = "40px" })%>
</label>
<label class="formLabel" for="Info">Info:
<br />
<%= Html.TextArea("Info", Model.Info, 15, 130, null) %>
</label>
<br />
<label class="formLabel" for="WebSite">Web site address:
<%= Html.TextBox("WebSite", Model.WebSite, new { size = "40px" })%>
</label>
</div>
</div>
<div class="clear" ></div>
<div id="footer" style="text-align: left">
<input type="submit" value="Save" />
<%=Html.ActionLink("Back to List", "List") %>
</div>
<% } %>
</asp:Content>
The strange thing is that the create method renders the "edit" view and the tinyMCE edit appears correctly. But when the edit action method renders the "edit" view, the view appears as you would expect - but without the tinyMCE editor.
No errors appear in FireBug, I get exactly the same behaviour in IE.
I also tried removing the $("#tabs").tabs() line but it made no difference.
It could be related to this line:
script_url: '../../Scripts/tiny_mce/tiny_mce.js',
Since the problem is in the Edit view, maybe the extra parameter adds one level to the folder structure.
Why don't you try:
script_url: '/Scripts/tiny_mce/tiny_mce.js',

MVC - Partial Views

I have a Viewpage menu with controller Menucontroller. I have a partialView ViewItems which is strongly typed as object BagItem with contro ller BagItem.
I am trying to render the partial View from View page(Menu.aspx) and can't render partial View. Any help would be greatly appreciated.New to MVC. Here is the code
Menu.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MenuItem>>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
OrderMenu
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
OrderMenu</h2>
<div>
<table>
<tr>
<td>
<% List<BagItem> sb = new List<BagItem>(); %>
<% Html.RenderPartial("../ShoppingBagItem/ViewItems", sb, (ViewDataDictionary)ViewData["BagItems"]);%>
</td>
</tr>
</table>
</div>
partialView
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<GuessCafe.Library.BagItem>>" %>
<body>
<div id="divLatestStocks">
<%foreach (var item in Model)
{ %>
<ul>
<li>
<%= item.ShoppingBagItemId %>
</li>
</ul>
<%}
%>
</div>
</body>
BagItemController
public ActionResult GetShoppingBagItems()
{
ViewData["BagItems"] = ObjectContext.BagItem.ToList();
return View(ViewData["BagItems"]);
}
I think what you want is simply this:
<% Html.RenderPartial("ViewItems", ViewData["BagItems"]); %>
This is assuming your partial view is named ViewItems.ascx.
You can remove the following line from your view:
<% List<BagItem> sb = new List<BagItem>(); %>
Update: your partial view should not contain <body>...</body> tags. These should either be on the master page.
public ActionResult GetShoppingBagItems()
{
ViewData["BagItems"] = ObjectContext.BagItem.ToList();
return View(ViewData["BagItems"]);
}
This is a bad practice at all. If you want pass Model to view why just use ViewData Dictionary ?
You can simply write :
public ActionResult GetShoppingBagItems()
{
var BagItems = ObjectContext.BagItem.ToList();
return View(BagItems);
}

Resources