I'm using asp.net mvc also using jQuery ui dialog, i'm showing a partialview in a jQuery dialog but Firefox give me an error on these two files below. I post an Ajax.BeginForm() to server. on first post it's working fine but on sencond post it destroys my dialog.
jquery.validate.min.js
jquery.validate.unobtrusive.min.js
Error : jQuery is not defined
I dont have this problem in IE, please help.
#model MvcSmkApplication.Models.LoginModel
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Ajax.BeginForm("AuthenticateUser", "Members", new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "LoginForm",
OnSuccess = "OnSuccess",
}))
{
<div id="LoginForm">
#Html.ValidationSummary(true)
<fieldset>
<legend></legend>
<div class="editor-label">
#Html.LabelFor(model => model.EmailAddress)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.EmailAddress)<br />
#Html.ValidationMessageFor(model => model.EmailAddress)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Password)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Password)<br />
#Html.ValidationMessageFor(model => model.Password)
</div>
#foreach (ModelState modelState in ViewData.ModelState.Values)
{
foreach (ModelError error in modelState.Errors)
{
<div style="color: Red;">#error.ErrorMessage</div>
}
}
<div style="float: right;">
<input type="submit" value="Login" class="buttonAsLink" />
</div>
</fieldset>
</div>
}
<script type="text/javascript">
function OnSuccess(e) {
if (e["success"] == "true") {
$("#dialog").dialog("close");
location.reload();
}
else {
//alert('error');
}
}
</script>
You might try referencing your scripts like this:
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")"></script>
Here is the solution which I found it after 3 weeks research.
<script type="text/javascript">
function OnSuccess(e) {
if (e["success"] == "true") {
$("#dialog").dialog("close");
location.reload();
}
else {
$("#dialog").html(e);
return false;
}
}
</script>
Related
So I have this partial view:
#model QueryQuestionManager.Models.Domain.Answer
<script src="~/Scripts/DynamicList.js"></script>
<div class="editorRow">
#using (Html.BeginCollectionItem("Answers"))
{
<div>
#Html.LabelFor(x => x.AnswerText)
#Html.EditorFor(x => x.AnswerText)
</div>
delete
}
</div>
I want to load this partial view in my main view when someone clicks the link:
#model QueryQuestionManager.Models.Domain.Question
#{
ViewBag.Title = "Create";
}
<script src="~/Scripts/DynamicList.js"></script>
<br />
#using (Html.BeginForm(new { #class = "form", role = "form" }))
{
<div class="form-group">
<div class="editor-label">
#Html.LabelFor(m => m.QuestionText)
</div>
<div class="form-control">
#Html.TextBoxFor(m => m.QuestionText)
#Html.ValidationMessageFor(m => m.QuestionText)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.Category)
</div>
<div class="form-control">
#Html.TextBoxFor(m => m.Category)
#Html.ValidationMessageFor(m => m.Category)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.Answers)
</div>
<br />
<div id="editorRows">
#foreach (var item in Model.Answers)
{
#Html.Partial("EditorRow", item);
}
</div>
#Html.ActionLink("Add another...", "BlankEditorRow", "Question", new { id = "addItem" })
<br />
<input type="submit" value="Save" class="btn btn-success" />
</div>
}
<br />
<div>
#Html.ActionLink("Back to List", "Index", "Home")
</div>
This is the action result from the controller
public ActionResult BlankEditorRow()
{
return PartialView("EditorRow", new Answer());
}
And then I have a javascript file for the dynamic adding and deleting partial views.
$('#addItem').click(function () {
$.ajax({
url: this.href,
cache: false,
success: function (html) {
$('#editorRows').append(html);
}
});
return false;
});
$('a.deleteRow').live('click', function () {
$(this).parents('div.editorRow:first').remove();
return false;
});
But for some reason my partial view doesn't load inside my current view and it opens only the partial view.
Am I forgetting something?
I'm thinking you don't want that action link. I believe your jQuery click handler has the correct approach, but your action link is linking to your new URL (Question/BlankEditorRow) and you don't want that. Rather you just need to fetch this html, and insert it as you do, but WITHOUT navigating the main page to that URL.
Instead of the ActionLink, use an anchor tag and a hidden field.
<a id="addItem" href="#" />
<input type="hidden" id="partialViewAction" value="#Url.Action("BlankEditorRow","ControllerName")"
Now in your ajax call, instead of using the href property of the anchor, use the value of the hidden field.
url: $('#partialViewAction').val()
I am trying to use the Ajax.BeginForm to post data to a controller. In the case of specific errors, the form should re-render and display the custom error message that was added to the ModelState. For some reason, the error message is not displaying. I am even trying the following test case which is not working, am I missing something?
Edit.cshtml:
#using (Ajax.BeginForm("Edit", "UserInformation", FormMethod.Post, new AjaxOptions { HttpMethod = "Post", InsertionMode = InsertionMode.Replace, UpdateTargetId = "divFormContainerMain", LoadingElementId = "divPreLoader", OnSuccess = "onSuccess" }))
{
<div id="divPreLoader" style="display:none; text-align: center"><img src="#Url.Content("~/Content/images/preLoader.gif")" alt="" /></div>
<div id="divFormContainerMain">
#Html.Partial("_EditPartialView", Model)
</div>
<div class="buttonContainerBottom">
<span class="buttonContainerInner">
<input type="submit" id="btnSave" name="buttonPress" value="save" class="orangeButton" />
</span>
</div>
}
_EditPartialView.cshtml:
#Html.ValidationSummary(false)
<div id="divFormContainerUserInformation" class="formContainer">
<div class="labelContainer">
#Html.LabelFor(m => m.UserName)
</div>
<div class="elementContainer">
#Html.TextBoxFor(m => m.UserName, new { style = "width: 200px" })
#Html.ValidationMessageFor(m => m.UserName)
</div>
<div class="labelContainer">
#Html.LabelFor(m => m.Name)
</div>
<div class="elementContainer">
#Html.TextBoxFor(m => m.Name, new { style = "width: 200px" })
#Html.ValidationMessageFor(m => m.Name)
</div>
<div class="labelContainer">
#Html.LabelFor(m => m.EmailAddress)
</div>
<div class="elementContainer">
#Html.TextBoxFor(m => m.EmailAddress, new { style = "width: 200px" })
#Html.ValidationMessageFor(m => m.EmailAddress)
</div>
.
.
.
.
.
.
</div>
UserController:
[HttpPost]
public ActionResult Edit(UserModel userModel)
{
ModelState.AddModelError("", "This is a test");
return PartialView("_EditPartialView", userModel);
}
Where are your scripts added? In the _layout.cshtml or in the view itself? How are you loading the view? Is it with an ajax request to show a partial view?
If you are loading the partial view through ajax or as a partial view, maybe it could be that the partial view was not yet loaded in the jquery DOM model tree.
I would try the following. Change
<div id="divFormContainerMain">
#Html.Partial("_EditPartialView", Model)
</div>
to
<div id="divFormContainerMain">
#Html.Partial("_EditPartialView", Model)
<script src="/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
</div>
or
<div id="divFormContainerMain">
#Html.Partial("_EditPartialView", Model)
#Scripts.Render("~/bundles/jqueryval") //if you have a bundle for it
</div>
My advice is anyway to load the validate and unobtrusive scripts only when you need them and not in the _layout.cshtml page.
Also don't forget to enable the following appSettings in the web.config
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
Make sure that you have included the jquery.unobtrusive-ajax.js script to your view after jquery itself. Otherwise the Ajax.BeginForm helper won't do what you think it does:
<script type="text/javascript" src="#Url.Content("~/scripts/jquery-YOUR-VERSION.js")"></script>
<script type="text/javascript" src="#Url.Content("~/scripts/jquery.unobtrusive-ajax.js")"></script>
I am making a page that stores clients. Clients can have domains and contacts and jobs.
Each contact/domain/job has edit/delete functionality.
I am using MVC 4 ASP.NET c#
each time you wish to edit/delete it launches a modal form.
The delete view for contact and domain is exactly the same except for the fields that it displays. The domain delete function does not fire anything when it is in partial view. But it succeeds when it is navigated to in the url as a regular view. the contact delete works fine in the partial view.
#model STClient.Models.Domain
#{
ViewBag.Title = "DeleteDomain";
}
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
#using (Html.BeginForm("DeleteDomain", "Client", FormMethod.Post)) {
<div class="modal-header">
<h2>Are you sure you want to delete?</h2>
</div>
<div class="modal-body">
<fieldset>
<div class="display-label">
<h3>
#Html.HiddenFor(model => model.server.ID)
#Html.HiddenFor(model => model.ID)
#Html.DisplayNameFor(model => model.Name):
#Html.DisplayFor(model => model.Name)
</h3>
</div>
<div class="display-label">
<h5>
#Html.DisplayNameFor(model => model.Registrar):
#Html.DisplayFor(model => model.Registrar)
</h5>
</div>
<div class="display-label">
<h5>
#Html.DisplayNameFor(model => model.PrimaryDNS):
#Html.DisplayFor(model => model.PrimaryDNS)
</h5>
</div>
<div class ="display-label">
<h5>
#Html.DisplayNameFor(model => model.SecondaryDNS):
#Html.DisplayFor(model => model.SecondaryDNS)
</h5>
</div>
</fieldset>
</div>
<div class="modal-footer">
<a class="btn" href="">Cancel</a>
<input class="btn btn-danger" type ="submit" value="Delete" />
</div>
}
this is on the details page where the delete link is for the domain.
<div class="modal fade" id="deleteDomain-modal"></div>
<script type="text/javascript">
$(function () {
$(".deleteDomain").click(function () {
$.ajax({
url: "/Client/DeleteDomain",
type: "GET",
data: {id: $(this).attr('id')},
dataType: "html",
success: function(e)
{
$("#deleteDomain-modal").html(e);
}
});
$("#deleteDomain-modal").modal();
});
});
</script>
And finally in the Client Controller
public ActionResult DeleteDomain(int id)
{
Domain domain = db.Domains.Find(id);
if (domain == null)
{
HttpNotFound();
}
return PartialView(domain);
}
[HttpPost, ActionName("DeleteDomain")]
public ActionResult DeleteDomainConfirmed(int id)
{
Domain domain = db.Domains.Find(id);
Server server = db.Servers.Find(id);
db.Domains.Remove(domain);
db.SaveChanges();
db.Servers.Remove(server);
db.SaveChanges();
LogDeleteDomain(domain, server);
return RedirectToAction("Index");
}
I think I had a similar problem. The reason was that parameter value was send as string and not as integer. I had to cast the value. So in your script code you may try to change the line:
data: {id: $(this).attr('id')},
to:
data: {id: parseInt($(this).attr('id'))},
That solved my problem.
I'm writing a tabbed page websystem in ASP.NET MVC3 and when I use ajax.BeginForm. The partial view isn't used to update the div but is show as a page.
What is wrong with the code? And why isn't it working? Thanks for the help!
I'm to figuring it out but can't get my head around it. Here is my code:
Controller:
public ActionResult Index(int id)
{
var shareholder = db.shareholder.Include("company").Include("groups");
return PartialView("Index", shareholder.ToList());
}
//
// GET: /Shareholder/Create
public PartialViewResult Create()
{
ViewBag.company_id = new SelectList(db.company, "id", "name");
ViewBag.groups_id = new SelectList(db.groups, "id", "name");
return PartialView("Create");
}
//
// POST: /Shareholder/Create
[HttpPost]
public ActionResult Create(shareholder shareholder)
{
if (ModelState.IsValid)
{
db.shareholder.AddObject(shareholder);
db.SaveChanges();
return RedirectToAction("Index", new { id = shareholder.company_id });
}
ViewBag.company_id = new SelectList(db.company, "id", "name", shareholder.company_id);
ViewBag.groups_id = new SelectList(db.groups, "id", "name", shareholder.groups_id);
return PartialView("Create", shareholder);
}
partial View:
<script src="<%: Url.Content("~/Scripts/jquery.validate.min.js") %>" type="text/javascript"></script>
<script src="<%: Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js") %>"
type="text/javascript"></script>
<script src="<%: Url.Content("~/Scripts/MicrosoftAjax.js") %>" type="text/javascript"></script>
<script src="<%: Url.Content("~/Scripts/MicrosoftMvcValidation.js") %>" type="text/javascript"></script>
<% using (Ajax.BeginForm("Create", "Shareholder", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "tabs-2", InsertionMode = InsertionMode.Replace }))
{ %>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>shareholder</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.company_id, "company") %>
</div>
<div class="editor-field">
<%: Html.DropDownList("company_id", String.Empty) %>
<%: Html.ValidationMessageFor(model => model.company_id) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.name) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.name) %>
<%: Html.ValidationMessageFor(model => model.name) %>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
The view that is calling the partial view:
<script src="<%: Url.Content("~/Scripts/jquery.validate.min.js") %>" type="text/javascript"></script>
<script src="<%: Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js") %>"
type="text/javascript"></script>
<script src="<%: Url.Content("~/Scripts/MicrosoftAjax.js") %>" type="text/javascript"></script>
<script src="<%: Url.Content("~/Scripts/MicrosoftMvcValidation.js") %>" type="text/javascript"></script>
<script type="text/javascript">
var count = 2;
$(document).ready(function() {
$("#tabs").tabs();
getContentTab (1, "/Company/Details/<%=Model.id %>");
});
function getContentTab(index, url) {
$.ajax({
url: url,
success: function(result) {
for (var i = 0; i <= count; i++) {
document.getElementById("tabs-" + index).style.display = 'none';
}
$("#tabs-" + index).html(result);
document.getElementById("tabs-" + index).style.display = 'block';
$.validator.unobtrusive.parse("form");
},
error: function (xhr, status, error) {
alert(error);
},
});
}
</script>
<h2>
<%=Model.name %></h2>
<div id="tabs">
<ul>
<li><a href="#tabs-1" onclick="getContentTab(1, '/Company/Details/<%=Model.id %>');">
<%= VOWWebsite.Resource.Details%></a></li>
<li><a href="#tabs-2" onclick="getContentTab(2, '/Shareholder/Index/<%=Model.id %>');">
<%= VOWWebsite.Resource.Shareholders%></a></li>
</ul>
<div id="tabs-1">
</div>
<div id="tabs-2">
</div>
</div>
You have to include jquery.unobtrusive-ajax.min.js in your page:
<script src="<%: Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js") %>"
type="text/javascript"></script>
I use 'Ajax.BeginForm' in my application,but for some reason my form is redirecting to {controller}/{action} with right json data instead of start {OnComplete = "Add_OnComplete"}:
View:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.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>
#using (Ajax.BeginForm("Create", new AjaxOptions { OnComplete = "Add_OnComplete"}))
{
<fieldset>
<legend>Add</legend>
<div class="editor-label">
#Html.LabelFor(model => model.FullName)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.FullName)
#Html.ValidationMessageFor(model => model.FullName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Email)
#Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PhoneNumber)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.PhoneNumber)
#Html.ValidationMessageFor(model => model.PhoneNumber)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Status)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Status)
#Html.ValidationMessageFor(model => model.Status)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<script type="text/javascript">
function Add_OnComplete(context) {
var JsonAdd = context.get_response().get_object();
if (JsonAdd.Success) {
//TODO
}
}
</script>
Controller:
public PartialViewResult Create()
{
return PartialView();
}
[HttpPost]
public JsonResult Create(Subscribe model)
{
if (ModelState.IsValid)
{
_entity.CreateSubscribe(model, SubscribeStatus.Customer.GetHashCode());
var message = new Message(MailSubject, MailBody, model.Email);
message.Send();
}
return Json(new
{
Success = true,
Message = "The person has been added!"
});
}
What I do wrong ? And what am I missing?
Thanks.
Remove that get_response().get_object() stuff.
Use just context.Success