Render a partial view inside a Jquery modal popup on top of a parent view - asp.net-mvc

I am rendering a partial view on top of the parent view as follows on a button click:
$('.AddUser').on('click', function () {
$("#AddUserForm").dialog({
autoOpen: true,
position: { my: "center", at: "top+350", of: window },
width: 1000,
resizable: false,
title: 'Add User Form',
modal: true,
open: function () {
$(this).load('#Url.Action("AddUserAction", "UserController")');
}
});
});
When user click AddUser button i am giving a jquery modal pop up with partial view rendered in it. But when user click save on partial view I am saving the entered information into database. But i have to show the pop up again on the parent view to add another user, until they click on cancel. Please help me how to load the partial view on top of the parent view.
Thanks

I suggest you create a jquery ajax function to post form data, then use the call back function to clear the form data. This way unless the user clicks the cancel button, the dialog is always showing.
See below example:
Main View
<button class="AddUser">Add User</button>
<div id="AddUserForm"></div>
Partial View (AddUserPartialView)
#model Demo.Models.AddUserViewModel
<form id="myForm">
<div id="AddUserForm">
#Html.LabelFor(m => m.Name)
#Html.TextBoxFor(m => m.Name)
</div>
</form>
Js file
$('.AddUser').on('click', function () {
$("#AddUserForm").dialog({
autoOpen: true,
position: { my: "center", at: "top+350", of: window },
width: 1000,
resizable: false,
title: 'Add User Form',
modal: true,
open: function () {
$(this).load('#Url.Action("AddUserPartialView", "Home")');
},
buttons: {
"Add User": function () {
addUserInfo();
},
Cancel: function () {
$(this).dialog("close");
}
}
});
return false;
});
function addUserInfo() {
$.ajax({
url: '#Url.Action("AddUserInfo", "Home")',
type: 'POST',
data: $("#myForm").serialize(),
success: function(data) {
if (data) {
$(':input', '#myForm')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
}
}
});
}
Action
public PartialViewResult AddUserPartialView()
{
return PartialView("AddUserPartialView", new AddUserViewModel());
}
[HttpPost]
public JsonResult AddUserInfo(AddUserViewModel model)
{
bool isSuccess = true;
if (ModelState.IsValid)
{
//isSuccess = Save data here return boolean
}
return Json(isSuccess);
}
Update
If you want to show the error message when errors occurred while saving the data, you could change the Json result in AddUserInfo action like below:
[HttpPost]
public JsonResult AddUserInfo(AddUserViewModel model)
{
bool isSuccess = false;
if (ModelState.IsValid)
{
//isSuccess = Save data here return boolean
}
return Json(new { result = isSuccess, responseText = "Something wrong!" });
}
then add a div element in your partial view:
#model MyParatialView.Controllers.HomeController.AddUserViewModel
<div id="showErrorMessage"></div>
<form id="myForm">
<div id="AddUserForm">
#Html.LabelFor(m => m.Name)
#Html.TextBoxFor(m => m.Name)
</div>
</form>
finally, the addUserInfo JS function should be like :
function addUserInfo() {
$.ajax({
url: '#Url.Action("AddUserInfo", "Home")',
type: 'POST',
data: $("#myForm").serialize(),
success: function (data) {
if (data.result) {
$(':input', '#myForm')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
} else {
$("#showErrorMessage").append(data.responseText);
}
}
});
}

Related

jQuery dialog won't switch to modal after initialization

If I initialize my modal like this:
$("#dlg").dialog({
open: function (e) {
$(this).load('mvc action url');
},
close: function () {
$(this).dialog('destroy').empty();
},
modal: true
});
...it initializes as modal. However, if I leave out modal: true at initialization and try to set modality after the dialog is already open like this:
$("#dlg").dialog("option", "modal", true);
...it doesn't work. I know it's being set because I can alert the modal value after setting it. I'm also properly referencing jquery-ui's library because I can open it as modal at initialization.
Edit
Here's a fiddle:
http://jsfiddle.net/s9zmfkdn/1/
When you click open initially, it shows as modal as expected. Now remove the line as I instruct in the fiddle. When you open the dialog this time and then click Make it modal, nothing happens
So there are a few things that are causing this to fail to work as you anticipated.
You wrapped the initialization of the dialog in a function, so it was not globally available to other functions.
You destroy the dialog upon close, so it no longer exists to allow the change of the modal option.
It's not clear why you're doing it this way and I suspect there is something you're not sharing. Regardless, here is one example that works:
http://jsfiddle.net/Twisty/s9zmfkdn/2/
HTML
<div id="basesystem" title="whatever" style="display:none"></div>
<input type="button" class="moduleloader" value="Open" />
<input id="makemodal" type="button" value="Remove Modal" />
JavaScript
$(function() {
$("#basesystem").dialog({
open: function(e) {
$(this).html('<span>hello</span>');
},
close: function() {
$(this).empty();
},
modal: true,
autoOpen: false
});
$("#makemodal").click(function() {
if ($("#basesystem").dialog("option", "modal")) {
$("#basesystem").dialog("option", "modal", false);
$(this).val("Make Modal");
} else {
$("#basesystem").dialog("option", "modal", true);
$(this).val("Remove Modal");
}
});
$(".moduleloader").click(function() {
$("#basesystem").dialog("open");
});
});
Now if you need, you can define the object more globally and manipulate it like so:
http://jsfiddle.net/Twisty/s9zmfkdn/4/
HTML
<div id="basesystem" title="whatever" style="display:none"></div>
<input type="button" class="moduleloader" value="Open" />
<input id="makemodal" type="button" value="Remove Modal" data-modal="true" />
JavaScript
$(function() {
var $diag = $("#basesystem");
$(".moduleloader").click(function() {
$diag.dialog({
open: function(e) {
$diag.html('<span>hello</span>');
},
close: function() {
$diag.dialog("destroy").empty();
},
modal: $("#makemodal").data("modal")
});
});
$("#makemodal").click(function() {
if ($(this).data("modal")) {
$(this).data("modal", false);
$(this).val("Make Modal");
} else {
$(this).data("modal", true);
$(this).val("Remove Modal");
}
});
});
This creates a new dialog every time and destroys it upon close. The only difference is that modal preference is stored someplace. You could also do this by storing it in global variable too.
Update 1
Based on your description, what you'll want to do is remove or create the ui-widget-overlay element.
Try this on for size: http://jsfiddle.net/s9zmfkdn/5/
$(function() {
function removeOverlay() {
$(".ui-widget-overlay").remove();
}
function setOverlay() {
if ($(".ui-widget-overlay").length) {
return false;
}
var $ov = $("<div>", {
class: "ui-widget-overlay"
}).css({
width: $(window).width(),
height: $(window).height(),
zIndex: 1001
});
$("body").append($ov);
}
$("#basesystem").dialog({
open: function(e) {
$(this).html('<span>hello</span>');
var $button = $("<a>", {
href: "#"
}).html("Toggle Modal").button().click(function() {
if ($(".ui-widget-overlay").length) {
removeOverlay();
} else {
setOverlay();
}
}).appendTo($(this));
},
close: function() {
$(this).empty();
},
modal: true,
autoOpen: false
});
$("#makemodal").click(function() {
if ($("#basesystem").dialog("option", "modal")) {
$("#basesystem").dialog("option", "modal", false);
$(this).val("Make Modal");
} else {
$("#basesystem").dialog("option", "modal", true);
$(this).val("Remove Modal");
}
});
$(".moduleloader").click(function() {
$("#basesystem").dialog("open");
});
});

ASP.NET MVC 5: Client Validation is not working for a view model (annotations) [duplicate]

I have JQuery popups and i want to put required field validations on it and for this i have set required attributes in model and have also set the validation message for them in the view but that required field validations are not working on popups. Required field validation is working fine on forms other than JQuery Popups....Please guide me that what should i do to tackle this issue...Following is my code.
Model
[Display(Name = "Material Code")]
[Required(ErrorMessage = "*")]
public string MaterialCode { get; set; }
View
<li>
#Html.LabelFor(m => m.MaterialCode)
#Html.TextBoxFor(m => m.MaterialCode)
#Html.HiddenFor(m => m.MaterialCodeId)
</li>
and following is my cod eto open a JQuery popup.
$('#btnAddCharge').on('click', function (event) {
event.preventDefault();
var actionURL = '#Url.Action("Edit", "Charges", new { Id = 0, #ticketId = #TicketId, UserId = UserId })';
$(dialogBox).dialog({
autoOpen: false,
resizable: false,
title: 'Edit',
modal: true,
show: "blind",
width: 'auto',
hide: "blind",
open: function (event, ui) {
$(this).load(actionURL, function (html) {
$('form', html).submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (res) {
if (res.success) {
$(dialogBox).dialog('close');
}
}
});
return false;
});
});
}
});
$(dialogBox).dialog('open');
});
The validator is parsed when the page is initially loaded. When you add dynamic content you need to reparse the validator. Modify your script to include the following lines after the content is loaded
$(this).load(actionURL, function (html) {
// Reparse the validator
var form = $('form');
form.data('validator', null);
$.validator.unobtrusive.parse(form);
$('form', html).submit(function () {
....
Side note: The code you have shown does not include #Html.ValidationMessageFor(m => m.MaterialCode) but I assume this is included.

Autocomplete results will not be displayed inside asp.net mvc partial view

I have the following script that is rendered inside my _layout view:-
$(document).ready(function () {
$("input[data-autocomplete-source]").each(function () {
var target = $(this);
target.autocomplete({
source: target.attr("data-autocomplete-source"),
minLength: 1,
delay: 1000
});
});
});
and i added the following field to apply autocomplete on it:-
<input name="term" type="text" data-val="true"
data-val-required= "Please enter a value."
data-autocomplete-source= "#Url.Action("AutoComplete", "Staff")" />
now if i render the view as partial view then the script will not fire, and no autocomplete will be performed, so i added the autocomplete inside ajax-success as follow:-
$(document).ready(function () {
$(document).ajaxSuccess(function () {
$("input[data-autocomplete-source]").each(function () {
var target = $(this);
target.autocomplete({
source: target.attr("data-autocomplete-source"),
minLength: 1,
delay: 1000
});
});
});
});
now after adding the AjaxSuccess the action method will be called, and when i check the response on IE F12 developers tools i can see that the browser will receive the json responce but nothing will be displayed inside the field (i mean the autocomplete results will not show on the partial view)?
EDIT
The action method which is responsible for the autocomplete is:-
public async Task<ActionResult> AutoComplete(string term)
{
var staff = await unitofwork.StaffRepository.GetAllActiveStaff(term).Select(a => new { label = a.SamAccUserName }).ToListAsync();
return Json(staff, JsonRequestBehavior.AllowGet);
}
EDIT2
here is the script which is responsible to show the modal popup:-
$(document).ready(function () {
$(function () {
$.ajaxSetup({ cache: false });
//$("a[data-modal]").on("click", function (e) {
$(document).on('click', 'a[data-modal]', function (e){
$('#myModalContent').css({ "max-height": screen.height * .82, "overflow-y": "auto" }).load(this.href, function () {
$('#myModal').modal({
//height: 1000,
//width: 1200,
//resizable: true,
keyboard: true
}, 'show');
$('#myModalContent').removeData("validator");
$('#myModalContent').removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse('#myModalContent');
bindForm(this);
});
return false;
});
});
function bindForm(dialog) {
$('form', dialog).submit(function () {
$('.btn.btn-primary,.btn.btn-danger').prop("disabled", "disabled");
$('#progress').show();
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.ISsuccess) {
$('#myModal').modal('hide');
$('#progress').hide();
$('.btn.btn-primary,.btn.btn-danger').prop("disabled", false);
location.reload();
// alert('www');
} else {
$('#progress').hide();
$('#myModalContent').html(result);
$('.btn.btn-primary,.btn.btn-danger').prop("disabled", false);
bindForm();
}
}
});
}
else {
$('.btn.btn-primary,.btn.btn-danger').prop("disabled", false);
$('#progress').hide();
return false;
}
return false;
});
}
});
First, you don't need to wrap you ajaxSuccess fucntion in ready function.
Second, it's better to use POST when you get Json from server.
I tried to seproduce your problem, but have no luck.
Here how it works in my case(IE 11, MVC 4)
script on _Layout:
$(document).ajaxSuccess(function () {
$("input[data-autocomplete-source]").each(function () {
var target = $(this);
target.autocomplete({
source: function (request, response) {
$.post(target.attr("data-autocomplete-source"), request, response);
},
minLength: 1,
delay: 1000
});
});
});
Controller method:
[HttpPost]
public JsonResult AutoComplete()
{
return Json(new List<string>()
{
"1",
"2",
"3"
});
}
Partial View html:
<input name="term" type="text" data-val="true"
data-val-required="Please enter a value."
data-autocomplete-source="#Url.Action("AutoComplete", "Stuff")" />
UPDATE:
I find out what your problem is. Jquery autocomplete needs array of objects that have lable and value properties. So if you change your controller code like this and it will work.
public async Task<ActionResult> AutoComplete(string term)
{
var staff = await unitofwork.StaffRepository.GetAllActiveStaff(term)
.Select(a => new { label = a.SamAccUserName, value = a.SamAccUserName })
.ToListAsync();
return Json(staff, JsonRequestBehavior.AllowGet);
}
Also you can do it on client side with $.map jquery function you can see example here

Ajax displays div dialog in mvc view

Pretty new to ajax.
So I have this div:
<div id="authentication" title="Authentication" >
<b>Please Generate a new token to continue!</b>
<br /><br />
<table>
<tr>
<td>Token:</td>
<td><input type="text" id="txtToken"/></td>
</tr>
<tr>
<td></td>
<td><label id="lblError"></label></td>
</tr>
</table>
</div>
which is not being displayed on my mvc view because it is a being used as a dialogue box by Ajax code below:
$('#authentication').dialog({
autoOpen: true,
width:500,
resizable: false,
beforeclose : function() { return false; },
title: 'Authentication',
modal: true,
buttons: {
"Cancel": function () {
window.location.replace("#Url.Action("Index", "Home")");
},
"Submit": function () {
var token=$('#txtToken').val();
var dlg = $(this);
$.ajax({
type: 'POST',
data: { 'token': token},
dataType: 'json',
url: '#Url.Action("CheckNewToken", "Account")',
success: function (result) {
if(result==true)
{
window.parent.jQuery('#authentication').dialog('destroy');
}
else{
$('#lblError').html("Incorrect credentials. Please try again");
}
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
}
}
});
However when the codes goes to success and result == result, the dialog box is destroyed but the div (dialog box) is then being displayed on my view which I don't want. What am I doing wrong?
Close the dialog and then destroy. This will hide the dialog completely and then destroy its dialog features. if you just do .dialog('destroy') it will just remove the dialog functionality completely and display the element as is on the page but it wont hide.
success: function (result) {
if(result==true)
{
$('#authentication').dialog('close').dialog('destroy');
}
else{
$('#lblError').html("Incorrect credentials. Please try again");
}
},
Another thing is beforeclose : function() { return false; }, you are returning false which will prevent the close event from happening. it should be beforeClose though you can remove it safely.
if the above doesnt work another option to remove the div is by subscribing to close event:-
$('#authentication').dialog({
autoOpen: true,
width:500,
resizable: false,
title: 'Authentication',
modal: true,
close:function(){
$(this).dialog('destroy').hide();
},
buttons: {
"Cancel": function () {
},
"Submit": function () {
var token=$('#txtToken').val();
var dlg = $(this);
$('#authentication').dialog('close');
}
}
});

Why are no validation errors shown with an Ajax form in my MVC?

What is wrong if no validation errors are shown when the submitted data is null/empty? An error should be shown.
In the code block result.success == false, should I reload the view or tell jQuery to invalidate my model?
From my Post action in the controller I return the model errors so I have them on the client side.
What should I do now?
I am using MVC 3.0 with latest jQuery/UI 1.7.2/1.8.20:
<script type="text/javascript">
$(document).ready(function () {
// the div holds the html content
var $dialog = $('<div></div>')
.dialog({
autoOpen: false,
title: 'This is the dialogs title',
height: 400,
width: 400,
modal: true,
resizable: false,
hide: "fade",
show: "fade",
open: function (event, ui) {
$(this).load('#Url.Action("Create")');
},
buttons: {
"Save": function () {
var form = $('form', this);
$.ajax({
url: $(form).attr('action'),
type: 'POST',
data: form.serialize(),
dataType: 'json',
success: function (result) {
// debugger;
if (result.success) {
$dialog.dialog("close");
// Update UI
}
else {
// Reload the dialog to show model/validation errors
} // else end
} // success end
}); // Ajax post end
},
"Close": function () {
$(this).dialog("close");
}
} // no comma
});
$('#CreateTemplate').click(function () {
$dialog.dialog('open');
// prevent the default action, e.g., following a link
return false;
});
});
</script>
my form is:
#using (Html.BeginForm("JsonCreate", "Template"))
{
<p class="editor-label">#Html.LabelFor(model => model.Name)</p>
<p class="editor-field">#Html.EditorFor(model => model.Name)</p>
<p class="editor-field">#Html.ValidationMessageFor(model => model.Name)</p>
}
My controller is:
[HttpGet]
public ActionResult Create()
{
return PartialView();
}
[HttpPost]
public ActionResult JsonCreate(Template template)
{
if (ModelState.IsValid)
{
_templateDataProvider.AddTemplate(template);
// success == true should be asked on client side and then ???
return Json(new { success = true });
}
// return the same view with model when errors exist
return PartialView(template);
}
The working version is:
I changed this in my $.ajax request:
// dataType: 'json', do not define the dataType let the jQuery infer the type !
data: form.serialize(),
success: function (result)
{
debugger;
if (result.success) {
$dialog.dialog("close");
// Update UI with Json data
}
else {
// Reload the dialog with the form to show model/validation errors
$dialog.html(result);
}
} // success end
The Post action has to look like this:
[HttpPost]
public ActionResult JsonCreate(Template template)
{
if (!ModelState.IsValid) {
return PartialView("Create", template);
_templateDataProvider.AddTemplate(template);
return Json(new { success = true });
}
}
Either return the partialview which is the form (success == false) or return the JSON which is success == true.
Someone could still return a list of items to update the UI on client side:
return Json(new { success = true, items = list});
You got to make sure you are returning a JSON data and not html or any other kind of data. Use the browsers console to find out more about your ajax request and response to be sure that you are getting the right response, as you expect.
well, the mistake I see is --
you are doing a return in the controller, you are supposed to do a
Response.Write(Json(new { success = true, items = list}));

Resources