ASP.NET MVC and tinyMCE - asp.net-mvc
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',
Related
Submit button is not disabling on ASP.NET MVC page
I have BackoutClaim page. On the Submit button click, I have to disable the button and from the POst method, when the response comes back, I have to enable button back. In the below code, the button is not disabling. Appreciate your responses. <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server"> <script type="text/javascript"> function TrimThatNameThenSubmit() { var tableName = $('#tableName').val().replace(/^\s+|\s+$/g, ""); $('#tableName').val(tableName); **$('#Submit').attr('disabled', 'disabled');** $('form:eq(0)').submit(); } </script> <% var messages = ViewData["messages"]; %> <% using (Html.BeginForm()) { %> <div> <div class="Spacer"></div> <div class="RevertCaseStateHeader" align="center"> <%= Html.TextBox("tableName", "Enter tableName to Backout Claim", new { #style = "width: 400px;" })%> <input type="button" value="Submit" onclick="javascript:TrimThatNameThenSubmit()"/> </div> <div class="RevertCaseStateSummary" align="center"> <% if (messages != null) { %> <%= Html.Encode(messages)%> <% } %> </div> </div> <% } %> </asp:Content>
Your jQuery is selecting the button with id=Submit which doesn't exist, change your button definition to: <input id="Submit" type="button" value="Submit" onclick="javascript:TrimThatNameThenSubmit()"/>
Deleting record using MVC Delete View
What I am trying to do is I am Listing all the record and then provide option to delete the record. When User clicks on Delete Link on Index page he is redirected to Delete Confirmation Page( Delete View created by MVC framework), now what I was expecting was when I click on Submit button on the Delete View it will come to my Delete Action of Controller with the object that needs to be deleted. But the problem is I am getting a object but all the properties are set to null. Below is the code: //GET public ActionResult DeleteUser (long id ) { return View(_repository.GetUserById(id)); } //POST [HttpPost] public ActionResult DeleteUser (UserDTO user) { _repository.DeleteUser(user.UserId); / return RedirectToAction("Index"); } I was expecting that one submit is clicked then Second (HttpPost) method will be called and user will be filled with the values, but that is not happening.. can anyone tell me what wrong am I doing ??? This is my Delete View Code <%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<RepositoryPatternSample.DTOs.UserDTO>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> DeleteUser </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>DeleteUser</h2> <h3>Are you sure you want to delete this?</h3> <fieldset> <legend>UserDTO</legend> <div class="display-label">UserId</div> <div class="display-field"><%: Model.UserId %></div> <div class="display-label">Username</div> <div class="display-field"><%: Model.Username %></div> <div class="display-label">FirstName</div> <div class="display-field"><%: Model.FirstName %></div> <div class="display-label">LastName</div> <div class="display-field"><%: Model.LastName %></div> </fieldset> <% using (Html.BeginForm()) { %> <p> <input type="submit" value="Delete User" /> | <%: Html.ActionLink("Back to List", "Index") %> </p> <% } %> </asp:Content>
Your properties are out of the form post. That's why you see the model null. Personally instead of passing all the model properties I would pass only the id. Something like that <% using (Html.BeginForm()) { %> <p> <%: Html.HiddenFor(model=> model.UserId) %> <input type="submit" value="Delete User" /> | <%: Html.ActionLink("Back to List", "Index") %> </p> <% } %> and your controller would be [HttpPost] public ActionResult DeleteUser (int userId) { _repository.DeleteUser(userId); return RedirectToAction("Index"); }
I am using asp.net MVC 1.0 and want to apply some jquery or javascript in below code?
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ens.ContactPerson>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Edit </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Edit</h2> <%if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated) { %> <%= Html.ValidationSummary("Edit was unsuccessful . Please correct the errors and try again.")%> <% using (Html.BeginForm()) {%> <fieldset> <legend>Fields</legend> <p> <%= Html.Hidden("Id", Model.Id)%> <%= Html.ValidationMessage("Id", "*")%> </p> <p> <label for="FirstName">FirstName:</label> <%= Html.TextBox("FirstName", Model.FirstName)%> <%= Html.ValidationMessage("FirstName", "*")%> </p> <p> <label for="MiddleName">MiddleName:</label> <%= Html.TextBox("MiddleName", Model.MiddleName)%> <%= Html.ValidationMessage("MiddleName", "*")%> </p> <p> <label for="LastName">LastName:</label> <%= Html.TextBox("LastName", Model.LastName)%> <%= Html.ValidationMessage("LastName", "*")%> </p> <p> <label for="DateOfBirth">DateOfBirth:</label> <%= Html.TextBox("DateOfBirth", String.Format("{0:g}", Model.DateOfBirth))%> <%= Html.ValidationMessage("DateOfBirth", "*")%> </p> <p> <label for="ContactPersonType">ContactPersonType:</label> <%= Html.DropDownList("ContactPersonType")%> <%= Html.ValidationMessage("ContactPersonType", "*")%> </p> <p> <input type="submit" value="Save" /> </p> </fieldset> <% } %> <div> <%=Html.ActionLink("Back to List", "All")%> </div> <%} %> </asp:Content> can i apply some javascript or jquery here such that after click on submit button, it must checks for the values are valid , if can do so. pls give code for the validation of last name field...this should not be empty. i tried with this function but it dindt work.... protected void ValidateContact(ens.ContactPerson contactToValidate) { if (contactToValidate.FirstName.Trim().Length == 0) ModelState.AddModelError("FirstName", "First name is required."); if (contactToValidate.LastName.Trim().Length == 0) ModelState.AddModelError("LastName", "Last name is required."); if (contactToValidate.MiddleName.Trim().Length == 0) ModelState.AddModelError("MiddleName", "Invalid phone number."); if (contactToValidate.DateOfBirth.ToString().Trim().Length == 0) ModelState.AddModelError("Email", "Invalid email address."); }
Probably, You can force validate entire form with Sys.Mvc.FormContext.getValidationForForm. Example: http://weblogs.asp.net/imranbaloch/archive/2010/07/11/asp-net-mvc-client-side-validation-with-dynamic-contents.aspx You will need some JavaScript references. Follow this http://www.gregshackles.com/2010/02/validating-hidden-fields-in-asp-net-mvc-2/ After that, you can just call any javascript method on submit button, do javascript validation and then submit the form. <script type="text/javascript" language="javascript"> function ValidateLastName(name) { //all validation here var form = document.forms[0]; form.action = '/AddressType/Create'; form.submit(); } </script> OR may be one of these may help, http://forums.asp.net/t/1538157.aspx/1 My Own javascript validation + MicrosoftMvcValidation . Is it possible ? How
You are going to want to make the submit button a regular button and onclick call a javascript function that validates your fields. If the validation passes you can submit the form with $("#myForm").submit(). You can do something like var lastName = $("#LastName").val() to get the value in your last name textbox and then test the value in lastName.
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.
Error while loading Partial View based on the Tab selected on ASP.NET MVC page
I am new to MVC and trying to load a partial view based on the tab selected. Here are the two tabs (Prodcuts and Doc Types) and Two partial views (NavMenuProduct.ascx and NavMenuDocType.ascx). The default page is: Index.aspx My code is not loading the Partial view. I would appreciate if someone has any code sample for this. Here is the Javascript: <script type="text/javascript"> $(function () { var $tabs = $("#tabs").tabs({ select: function (e, ui) { hdnTabSelected.value = ui.index; alert(hdnTabSelected.value); } }); }); </script> Html Code: <table class="tableNoBorder" width="100%"> <!--Header Dashboard--> <tr> <td colspan="2"> <div id="container"> <h1>DocShare</h1> <div id="welcome">Welcome, <%=new CacheUser().GetLoginUser().CommanName%></div> </div> </td> </tr> <!--Tabs Section for Products and DocType--> <tr> <td colspan=2> <DIV id=tabs> <UL> <LI><A href="#" >Products</A></LI> <LI>Doc Type</LI> </DIV> </td> </tr> <!--Left Menu Navigation and Main Content--> <tr> <td valign="top" width="200px"> <div > <input type="hidden" id = "hdnTabSelected" runat="Server" /> <%-- If TabSelected = 0, load Product Menu, otherwise Load DocType Menu--%> <%if (hdnTabSelected.Value == "0") %> <% Html.RenderAction("NavMenuProduct","Home"); %> <% else %> <% Html.RenderAction("NavMenuDocType","Home"); %> </div> </td> <td valign="top" width ="100%" > <div id="content"> <asp:ContentPlaceHolder ID="MainContent" runat="server"></asp:ContentPlaceHolder> </div> </td> </tr> </table>
What you look to be doing is a standard master page ... I would open up a file new MVC and look at how it does that with the home and about tabs ... Master : <div id="header"> <div id="title"> <h1>My MVC Application</h1> </div> <div id="logindisplay"> <% Html.RenderPartial("LogOnUserControl"); %> </div> <div id="menucontainer"> <ul id="menu"> <li><%: Html.ActionLink("Home", "Index", "Home")%></li> <li><%: Html.ActionLink("About", "About", "Home")%></li> </ul> </div> </div> <div id="main"> <asp:ContentPlaceHolder ID="MainContent" runat="server" /> <div id="footer"> </div> </div> </div> about <asp:Content ID="aboutTitle" ContentPlaceHolderID="TitleContent" runat="server"> About Us </asp:Content> <asp:Content ID="aboutContent" ContentPlaceHolderID="MainContent" runat="server"> <h2>About</h2> <p> Put content here. </p> </asp:Content>
Remove the runat="server" from the above hidden input. The problem is that the rendered html and the javascript are not matching. This should work the first time the page loads, however the rendered id for the hidden input will look like ctl00$MainContent$hdnTabSelected which does not match hdnTabSelected.value in the javascript. You could change the javascript to this, but I recommend against it <script type="text/javascript"> $(function () { var $tabs = $("#tabs").tabs({ select: function (e, ui) { <%=hdnTabSelected.ClientID %>.value = ui.index; alert(<%=hdnTabSelected.ClientID %>.value); } }); }); </script>
It isn't obvious what is wrong according to you question, but at the first glance I think you should replace your calls to Html.RenderAction to calls to Html.Action. The difference between the two is that Html.RenderAction will render the result directly to the Response (which is more efficient if the action returns a large amount of HTML) whereas Html.Action returns a string with the result. Haaked has a blog-post with more details.