Open Telerik Window - asp.net-mvc-3

I hope you can assist me with one dillema. I´m going to write a bunch of code before I ask my question below :)
When something is clicked on my page:
<input type='button' value='1' name='derp1' onclick='OpenTelerikWindow(1)' />
<br/>
<input type='button' value='2' name='derp2' onclick='OpenTelerikWindow(2)' />
I open Telerik Window with Jquery:
function OpenTelerikWindow(arg) {
var url = '/Controller/Derp/';
$.ajax({
type: "GET",
url: url,
dataType: "html",
data: { id: arg }
success: function (data) {
$('#PaymentWindow').data("tWindow").content(data);
$('#PaymentWindow').data("tWindow").center().open().refresh();
}
});
}
My Controller ActionResult:
public ActionResult Derp(int id)
{
SomeModel someModel = _GetModel(id);
return PartialView("Derp", someModel)
}
And then the content of my Telerik Window goes something like this:
#SomeModel
<div id="theDerpina">
<div>
//Some Stuff
#using (Ajax.BeginForm("Derpina1", "Controller", new { id = SomeModel.id }, new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "theDerpina",
InsertionMode = InsertionMode.Replace
}, new { id = "feedback-form" }))
{
//Some Stuff
<button type="submit" > Submit</button>
<br/>
<button type="button" > CloseWindow </button>
}
</div>
<div>
//More Stuff
#using (Ajax.BeginForm("Derpina2", "Controller", new { id = SomeModel.id }, new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "theDerpina",
InsertionMode = InsertionMode.Replace
}, new { id = "feedback-form" }))
{
//Different Stuff
<button type="submit" > Submit</button>
<br/>
<button type="button" > CloseWindow </button>
}
</div>
</div>
My two other Controller Actions:
public ActionResult Derpina1(int id)
{
SomeModel someModel = _GetModel(id);
if(ModelState.IsValid)
{
//DoStuff
return View("SomeOtherView");
}
else
{
return PartialView("Derp", someModel);
}
}
public ActionResult Derpina2(int id)
{
SomeModel someModel = _GetModel(id);
if(ModelState.IsValid)
{
//DoDifferentStuff
return View("SomeOtherView");
}
else
{
return PartialView("Derp", someModel);
}
}
When I open the Window once, everything works fine. However if I were to open the Window, close it, and then open it again then weird things happen. Let´s say for instance that I clicked the submit button for Derpina1, I would receive two calls to that particular Controller action. If I monitor the console in Firebug I see two separate calls to my controller action. Then the same thing would happen if I would close the Window one more time, open it again, and submit again, my controller action would now receive 4 calls to my controller action.
Perhaps you guys can point to the right direction. Should I open the Telerik Window in a different way, also should I use different method to return ModelError were that to happen? (because I´m faced with the same behaviour if I get a ModelError)

I managed to find out the solution after googling a while. All I did was creating a Window on the fly from within the script, and then destroying it after I have used it, like so:
function OpenTelerikWindow(arg) {
var url = '/Controller/Derp/';
$.ajax({
type: "GET",
url: url,
dataType: "html",
data: { id: arg }
success: function (data) {
var paymentWindow = $("<div id='PaymentWindow'></div>").tWindow({
title: "Payment",
contentUrl: '',
html: data,
modal: true,
resizable: false,
draggable: true,
width: 500,
height: 640,
onClose: function (e) {
e.preventDefault();
paymentWindow.data('tWindow').destroy();
}
});
paymentWindow.data('tWindow').center().open();
}
});
}

Related

ASP.NET MVC ViewBag values not being displayed in view after Ajax call

I have following view and controller code:
Index.cshtml
#using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<span style="color:green; font-weight:bold;" id="Message">#ViewBag.Message</span>
<input type="text" id="txtMessage" />
<input type="submit" id="btnSubmit" value="Submit" />
}
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$('#btnSubmit').click(function (event) {
$.ajax({
type: "POST",
url: "/Home/Create",
dataType: "json",
contentType: "application/json; charset=utf-8",
async: false,
data: JSON.stringify({
'message': $('#txtMessage').val()
})
});
});
</script>
Controller code:
public class HomeController : Controller
{
public ActionResult Index(string message)
{
return View();
}
[HttpPost]
public ActionResult Create(string message)
{
ViewBag.Message = message;
return View("Index");
}
}
After clicking the button and making ajax call I'm not able to see the message set in the Create method to ViewBag.Message inside the index view.
If you are using Begin form and button type as submit then why write ajax method?
Remove your btnSubmit click from javascript code and use textbox as TextBoxFor,
#Html.TextBoxFor(m => m.message, new { #class = "form-control" })
it should work.
Update Answer for without strongly type
As per code, you are using Begin Form so not required to ajax call.
So first remove javascript code or if you keep that code so no meaning of that.
Now need to update the following line:
<input type="text" id="txtMessage" **name = "txtMessage"** />
And in the controller code post method the following name should be the same.
[HttpPost]
public ActionResult Create(**string txtMessage**)
{
ViewBag.Message = **txtMessage**;
return View("Index");
}

Model validation in Asp.Net Core before making an Ajax call from java script

Below is the sample code, i am calling this code on button click event. My question is, can i validate my viewmodel object before making ajax call? i can see model errors in java script, not sure how to check.
My viewmodel class properties has Data Annotation Validator Attributes. I don't want make ajax call if the viewmodel is not valid, want to check (ModelState.IsValid) in java script code, before making ajax call.
Any help, would be greatly appreciated.
$(function () {
$("#btnGet").click(function () {
var viewModelobject = {};
viewModelobject.Name = $("#txtName").val();
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: viewModelobject,
contentType: "application/json",
dataType: "json",
success: function (response) {
alert("Hello")
}
});
});
}
ModelState.IsValid is server side code.Browser has no idea about what it is,so you could not validate ModelState in client side. You can use Jquery Validation at client side.
Here is a working demo:
1.Model:
public class UserModel
{
[Required(ErrorMessage = "The Name field is required.")]
[Display(Name = "Name")]
public string Name { get; set; }
}
2.View(Index.cshtml):
#model UserModel
<form id="frmContact">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" id="txtName" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<button type="submit" class="btn btn-secondary" id="btnGet">Click</button>
</div>
</form>
#section Scripts
{
#*you could also add this partial view*#
#*#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}*#
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"></script>
<script>
$(function () {
$('#btnGet').click(function () {
if ($("#frmContact").valid()) {
$('#frmContact').submit();
}
else {
return false;
}
});
$("#frmContact").on("submit", function (event) {
event.preventDefault();
var viewModelobject = {};
viewModelobject.Name = $("#txtName").val();
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: JSON.stringify(viewModelobject),
contentType: "application/json",
dataType: "json",
success: function (response) {
alert("Hello")
}
});
});
})
</script>
}
3.Controller:
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult AjaxMethod([FromBody]UserModel user)
{
//do your stuff...
return Json(user);
}
}
Result:
Please use jQuery form validation as shown below inside the button click callback:
var form = $('form[name="' + formName + '"]');
form.validate();
if (form.valid()) {
//Do something if the form is valid
}
else {
//Show validation error messages if the form is in-valid
}

MVC Controller receiving null values from ajax

I'm trying to send an Ajax post to mvc controller contains two parameters.
First parameter: serialized model (Folder)
Second parameter: Array (Periods)
The problem is the controller received null values in the first parameter:
Javascript code :
var data = JSON.stringify({
Folder: $('#Folder').serialize(),
Periods: periodsArr
});
function save(data) {
return $.ajax({
type: 'POST',
//cache: false,
contentType: 'application/json', //Without folder not empty and period is empty
//traditional: true,
//dataType: "json",
url: '#Url.Action("AddOrEditFolder", "Folder")',
data: data,
success: function (result) {
alert(result);
location.reload();
},
error: function () {
alert("Error!" + Error);
}
});
}
Html code:
<div class="card-body">
#using (Html.BeginForm(null, null, new { #id = string.Empty }, FormMethod.Post, new { #id = "Folder" }))
{
#Html.HiddenFor(model => model.FolderID)
<div class="row">
<label for="FirstNameAR" class="col-sm-2 control-label">الإسم الشخصي</label>
<div class="col-sm-4">
#Html.EditorFor(model => model.Trainee.FirstNameAR, new { htmlAttributes = new { #id= "FirstNameAr", #class = "form-control" } })
</div>
<label for="FirstNameFR" class="col-sm-2 control-label">الإسم العائلي</label>
<div class="col-sm-4">
#Html.EditorFor(model => model.Trainee.FirstNameFR, new { htmlAttributes = new { #id = "FirstNameFr", #class = "form-control" } })
</div>
</div> <br />
Controller code:
[HttpPost]
//[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrEditFolder(Folder Folder, Period[] Periods)
{
//Folder Folder = JsonConvert.DeserializeObject<Folder>(Obj);
using (InternshipsEntities dbContext = new InternshipsEntities())
{
//Some code here
}
}
How can I solve that problem ?
Use below code to create data object to pass in Ajax request.
var Folder = { };
$.each($('#Folder').serializeArray(), function() {
Folder[this.name] = this.value;
});
var data = {
Folder: Folder
Periods: periodsArr
};

How to use ajax to post Kendo upload files to controller

When i use ajax to post the form data to controller, i cannot get the files when using Kendo upload. I used IEnumerable but i only can get the date value and the file is null. May i know how to make it work? Thanks.
(I use ajax because i need call the onsuccess event)
//Here is the form control in view
<div class="editForm">
#using (Html.BeginForm("UpdateReportFix", "Defect", FormMethod.Post, new { id = "form" }))
{
#Html.HiddenFor(model => model.DefectFixID)
<div>
#Html.Label("Report Date")
</div>
<div>
#(Html.Kendo().DatePickerFor(model => model.ReportDate)
.Name("ReportDate")
.Value(DateTime.Now).Format("dd/MM/yyyy")
.HtmlAttributes(new { #class = "EditFormField" })
)
#Html.ValidationMessageFor(model => model.ReportDate)
</div>
<div>
#Html.Label("Photos")
<br />
<span class="PhotosMessage">System Allow 2 Pictures</span>
</div>
<div class="k-content">
#(Html.Kendo().Upload()
.Name("files") <-----i cannot get this value in controller
)
</div>
<br />
<div class="col-md-12 tFIx no-padding">
#(Html.Kendo().Button().Name("Cancel").Content("Cancel").SpriteCssClass("k-icon k-i-close"))
#(Html.Kendo().Button().Name("submit").Content("Submit").SpriteCssClass("k-icon k-i-tick"))
</div>
}
//script
$('form').submit(function (e) {
e.preventDefault();
var frm = $('#form');
$.ajax({
url: '#Url.Action("UpdateReportFix")',
type: 'POST',
data: frm.serialize(),
beforeSend: function () {
},
onsuccess: function () { },
success: function (result) { },
error: function () { }
});
});
For "Uploading files using Ajax & Retain model values after Ajax call and Return TempData as JSON" try the following example:
View:
#using (Html.BeginForm("Create", "Issue", FormMethod.Post,
new { id = "frmCreate", enctype = "multipart/form-data" }))
{
<div id="divMessage" class="empty-alert"></div>
#Html.LabelFor(m => m.FileAttachments, new { #class = "editor-label" })
#(Html.Kendo().Upload()
.HtmlAttributes(new { #class = "editor-field" })
.Name("files")
)
}
<script>
$(function () {
//Populate model values of the partialview after form reloaded (in case there is a problem and returns from Controller after Submit)
$('form').submit(function (event) {
event.preventDefault();
showKendoLoading();
var selectedProjectId = $('#ProjectID').val(); /* Get the selected value of dropdownlist */
if (selectedProjectId != 0) {
//var formdata = JSON.stringify(#Model); //For posting uploaded files use as below instead of this
var formdata = new FormData($('#frmCreate').get(0));
$.ajax({
type: "POST",
url: '#Url.Action("Create", "Issue")',
//contentType: "application/json; charset=utf-8", //For posting uploaded files use as below instead of this
data: formdata,
dataType: "json",
processData: false, //For posting uploaded files we add this
contentType: false, //For posting uploaded files we add this
success: function (response) {
if (response.success) {
window.location.href = response.url;
#*window.location.href = '#Url.Action("Completed", "Issue", new { /* params */ })';*#
}
else if (!response.success) {
hideKendoLoading();
//Scroll top of the page and div over a period of one second (1,000 milliseconds = 1 second).
$('html, body').animate({ scrollTop: (0) }, 1000);
$('#popupDiv').animate({ scrollTop: (0) }, 1000);
var errorMsg = response.message;
$('#divMessage').html(errorMsg).attr('class', 'alert alert-danger fade in');
$('#divMessage').show();
}
else {
var errorMsg = null;
$('#divMessage').html(errorMsg).attr('class', 'empty-alert');
$('#divMessage').hide();
}
}
});
}
else {
$('#partialPlaceHolder').html(""); //Clear div
}
});
});
</script>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Exclude = null)] Model viewModel, IEnumerable<HttpPostedFileBase> files)
{
//...
return Json(new { success = false, message = "Max. file size is 10MB" }, JsonRequestBehavior.AllowGet);
}

Partial view not rendering MVC razor

It's my first time using partial views and I am unable to get the actual partialview. The ajax function gets called, the controller gets hit, and an alert in the ajax call shows me that the partialview is there. But, with errors written to the console (or alert) my div remains just as empty.
My application is an MVC4 app, but I am pretty sure I've just done a silly mistake somewhere and its not MVC's fault :)
AFter a few hours of googling, I would really be happy anybody can help me get this working, and all tips/comments on code/ajax i greatly appreciated!
public PartialViewResult Groups()
{
var person = _userRepository.GetCurrentUser();
var connections = (from c in person.Person1 select c).ToList();
var groups = _context.Groups.Where(g => g.GroupId == 1);
var all = new GroupViewModel()
{
Connections = connections,
GroupDetailses = (from g in groups
select
new GroupDetails
{
Name = g.Name,
StartDate = g.StartDate,
StartedById = g.StartedById,
})
};
return PartialView("Groups",all);
}
My PartialView
#model Mvc4m.Models.GroupViewModel
<h2>Groups</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<h3>Create new Group</h3>
<div class="ui-widget">
<label for="group">Groupname: </label>
<input id="group" />
<button onclick="addGroup()">Add</button>
</div>
#foreach (var item in Model.GroupDetailses)
{
#Html.LabelFor(model => item.Name)<text> : </text>
#Html.DisplayFor(model => item.Name)
}
<script>
function addGroup() {
$.get(
"/Profile/AddGroup",
{
Name: $("#group").val()
});
location.reload();
};
</script>
My Ajax call on Profile/Index
#model Mvc4m.Models.ProfileView
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div id="test" style="background-color:Aqua; width:200px; height:100px"></div>
<button onclick="load()"></button>
<script type="text/javascript">
function load() {
$.ajax({
type: "GET",
url: '/Profile/Groups',
dataType: 'html',
success: function (response) {
$('#test').html(response);
alert(response);
},
error: function (xhr, status, error) {
alert(status + " : " + error);
}
});
}
</script>
Turns out the code works, a restart of visual studio did the trick! How I hate VS sometimes...

Resources