Triggering sweet alert message from the code behind for create method - asp.net-core

Thanks to the excellent answer by Rena in the previous question I am also asking how do I achieve the same effect of the sweet alert message box on the create controller action I tried with the code they gave in this.
Using JavaScript code behind asp.net core c#
But because the action create submits the form first it doesn't seem to like the trigger the alert.
swal({
title: "MIS",
text: "Case Created your Case Number is ",
icon: "warning",
buttons: true,
dangerMode: true,
})

just post the form with ajax after that jsut show the message you want
<form action="/your action url" method="post" id="formCreate">
...Yıur item inputs
<button type="submit"></button>
</form>
$("#formCreate").submit(function (event) {
event.preventDefault(); //prevent default action
var post_url = $(this).attr("action"); //get form action url
var request_method = $(this).attr("method"); //get form GET/POST method
var form_data = $(this).serialize(); //Encode form elements for submission
$.ajax({
url: post_url,
type: request_method,
data: form_data
}).done(function (response) { //
Swal.fire({
position: 'center',
icon: "warning",
text: "Case Created your Case Number is "+response.Id,
title: "MIS",
showConfirmButton: false,
timer: 1500,
}).then(() => {
window.location.reload(true);
})
});
});
in cotroller side you should return something like this
[HttpPost]
public IActionResult Create(Item item){
//create item
return Json(new {Id=item.id});
}

It seems you want to trigger the sweet alert when you click the submit button.
Here is a working demo:
Model:
public class Test
{
public int Id { get; set; }
public string Name { get; set; }
}
Index.cshtml:
#model IEnumerable<Test>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.Id">Edit</a> |
<a asp-action="Details" asp-route-id="#item.Id">Details</a> |
<a asp-action="Delete" asp-route-id="#item.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>
Create.cshtml:
#model Test
<h1>Create</h1>
<h4>Test</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<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" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<input type="button" onclick="Create()" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
<script>
function Create() {
swal({
title: "MIS",
text: "Case Created your Case Number is " + $("#Name").val(),
icon: "warning",
buttons: true,
dangerMode: true,
}).then((willCreate) => {
if (willCreate) {
var data = $('form').serialize();
$.ajax({
url: "/tests/create",
type: "POST",
data: data,
dataType: "html",
success: function () {
swal("Done!", "It was succesfully created!", "success")
.then((success) => {
window.location.href="/tests/index"
});
},
error: function (xhr, ajaxOptions, thrownError) {
swal("Error creating!", "Please try again", "error");
}
});
}
});
}
</script>
}
Controller:
public class TestsController : Controller
{
private readonly Mvc3_1Context _context;
public TestsController(Mvc3_1Context context)
{
_context = context;
}
// GET: Tests
public async Task<IActionResult> Index()
{
return View(await _context.Test.ToListAsync());
}
// GET: Tests/Create
public IActionResult Create()
{
return View();
}
// POST: Tests/Create
[HttpPost]
public async Task<IActionResult> Create(Test test)
{
if (ModelState.IsValid)
{
_context.Add(test);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(test);
}
}
Result:

Related

Pass Model from Partial View to the PageModel in Asp.Net Core Razor

I am trying to pass a Model from a Partial view back to the PageModel, but the results are always empty. In my main .cshtml, I have an 'Export' button that when clicked opens a bootstrap modal. Users then click a checkbox to select data to download. Here is my code:
In my cs, I set the partial with this code:
// FileContents contains a list of FileObjects (which include Name as IsSelected)
[BindProperty]
public FileContents ExportData { get; set; }
// Get method to return the partial.
// ExportData is passed as the model for the partial
public PartialViewResult OnGetExportModel()
{
ExportData = new FileContents();
ExportData.Files.Add(new FileObject("filename.txt", true);
return Partial("_ExportDetails", ExportData);
}
// Handles postback of the FileContents data
public IActionResult OnPostExportData(FileContents data)
{
//The count is always zero
Console.WriteLine(data.Files.Count);
}
The partial is a table with the file name and a checkbox:
#model FileContents
<div class="form-group">
<table>
<tbody>
#foreach (var item in Model.Files)
{
<tr>
<td class="clsChkBox" data-item="#item.Name">
#Html.CheckBoxFor(modelItem => item.IsSelected)
</td>
<td>#item.Name</td>
</tr>
}
</tbody>
</table>
</div>
In the main page .cshtml, I display the partial:
<div class="dvExport" id="exportPartial"></div>
The partial is set with a class from a script:
function ScriptExport() {
$('.dvExport').load('/index/exportmodel);
}
I have tried several ways to pass the FileContents model of the partial, back to the .cs file.
One by using a <form method=post" asp-page-handler="ExportData" asp-route-data="#Model.ExportData"> . When returned, data.Files is empty.
Second by calling an ajax postback. When serializing #Model.ExportData, the files are also empty.
How can I return FileContents model in the partial back to my main page?
I did a test using ajax, you can refer to my code below:
_ExportDetails.cshtml:
#model FileContents
<div class="form-group">
<table>
<tbody>
#foreach (var item in Model.Files)
{
<tr>
<td class="clsChkBox" data-item="#item.Name">
#Html.CheckBoxFor(modelItem => item.IsSelected)
</td>
//Add a class as an identifier
<td class="Name">#item.Name</td>
</tr>
}
</tbody>
</table>
</div>
Index.cshtml:
#page
#model IndexModel
#{
ViewData["Title"] = "Home page";
}
<button type="button" onclick="ScriptExport()">ScriptExport</button>
<button type="button" onclick="ScriptSubmit()">Submit</button>
<div class="dvExport" id="exportPartial"></div>
//Required
<div>#Html.AntiForgeryToken()</div>
<script>
function ScriptExport() {
$('.dvExport').load('index?handler=ExportModel');
}
function ScriptSubmit(){
var data = [];
$("table > tbody > tr").each(function() {
var Files = {
Name: $(this).find('.Name').text(),
IsSelected: $(this).find("input[type='checkbox']").prop("checked")
}
data.push(Files);
});
$.ajax({
type: "post",
url: "/index?handler=ExportData",
data: JSON.stringify({ Files: data }),
//Required
headers:
{
"RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
},
contentType: "application/json; charset=utf-8",
success: function(result)
{
alert("success");
},
error: function(error)
{
console.log(error);
}
});
}
</script>
Index.cshtml.cs:
public IActionResult OnPostExportData([FromBody]FileContents data)
{
Console.WriteLine(data.Files.Count);
return Page();
}
Test Result:

how to get data from database using ajax asp.net core

According to the following codes i have created the Get Handler in Index Model
public IActionResult OnGetCustomer(CustomerSearchModel searchModel)
{
CustomerCombine combine = new CustomerCombine
{
MyViewModels = _customerApplication.GetAll(searchModel)
};
return Partial("./Customer", combine);
}
and this is my Razor View:
#model CustomerCombine
<form asp-page="./Index" asp-page-handler="Customer"
method="get"
data-ajax="true"
data-callback=""
data-action="Refresh"
>
<div class="form-group">
<input asp-for="#Model.MySearchModel.FullName" class="form-control " placeholder="search..." />
</div>
<button class="customer-submit btn btn-success" type="submit">جستجو</button>
</form>
<table>
#foreach (var item in #Model.MyViewModels)
{
<tr>
<td>#item.Id</td>
<td>#item.FullName</td>
<td>#item.Mobile</td>
<td>#item.Email</td>
<td>#item.Address</td>
<td>#item.Image</td>
</tr>
}
</table>
My modal is displayed successfully,and i can see my database's data, but when i fill search field and click on search button , nothing happens
can any one help me plz?:)
and this is my jquey codes: i dont anything about Jquery and these codes were ready and now i dont knoe how i should use from it
$(document).on("submit",
'form[data-ajax="true"]',
function (e) {
e.preventDefault();
var form = $(this);
const method = form.attr("method").toLocaleLowerCase();
const url = form.attr("action");
var action = form.attr("data-action");
if (method === "get") {
const data = form.serializeArray();
$.get(url,
data,
function (data) {
CallBackHandler(data, action, form);
});
} else {
var formData = new FormData(this);
$.ajax({
url: url,
type: "post",
data: formData,
enctype: "multipart/form-data",
dataType: "json",
processData: false,
contentType: false,
success: function (data) {
CallBackHandler(data, action, form);
},
error: function (data) {
alert("خطایی رخ داده است. لطفا با مدیر سیستم تماس بگیرید.");
}
});
}
return false;
});
});
function CallBackHandler(data, action, form) {
switch (action) {
case "Message":
alert(data.Message);
break;
case "Refresh":
if (data.isSucceced) {
window.location.reload();
} else {
alert(data.message);
}
break;
case "RefereshList":
{
hideModal();
const refereshUrl = form.attr("data-refereshurl");
const refereshDiv = form.attr("data-refereshdiv");
get(refereshUrl, refereshDiv);
}
break;
case "setValue":
{
const element = form.data("element");
$(`#${element}`).html(data);
}
break;
default:
}
}
function get(url, refereshDiv) {
const searchModel = window.location.search;
$.get(url,
searchModel,
function (result) {
$("#" + refereshDiv).html(result);
});
}
1.The third parameter of $.get() is the success function.
2.There is no isSucceced property in your postback data. The postback data is the partial view html code. You need use $("xxx").html(data); to update the partial view code.
3.Model Binding binds the property by name, <input asp-for="#Model.MySearchModel.FullName"/> does not match the CustomerSearchModel searchModel.
public IActionResult OnGetCustomer(CustomerSearchModel MySearchModel)
Whole working demo and more details I have commented on the code pls check carefully:
Model
public class CustomerCombine
{
public List<MyViewModel> MyViewModels { get; set; }
public CustomerSearchModel MySearchModel { get; set; }
}
public class CustomerSearchModel
{
public string FullName { get; set; }
}
public class MyViewModel
{
public int Id { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
public string Address { get; set; }
public string Image { get; set; }
}
View(Index.cshtml)
#page
#model IndexModel
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
#Html.Partial("Customer",Model.CustomerCombine)
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
#section Scripts
{
<script>
$(document).on("submit",'form[data-ajax="true"]',function (e) {
e.preventDefault();
var form = $(this);
const method = form.attr("method").toLocaleLowerCase();
const url = form.attr("action");
var action = form.attr("data-action");
if (method === "get") {
const data = form.serializeArray();
$.get(url,data,function (data) {
console.log(data); //you can check the response data in Console panel
CallBackHandler(data, action, form);
});
} else {
var formData = new FormData(this);
$.ajax({
url: url,
type: "post",
data: formData,
enctype: "multipart/form-data",
dataType: "json",
processData: false,
contentType: false,
success: function (data) {
CallBackHandler(data, action, form);
},
error: function (data) {
alert("خطایی رخ داده است. لطفا با مدیر سیستم تماس بگیرید.");
}
});
}
return false;
});
//}); //remove this.......
function CallBackHandler(data, action, form) {
switch (action) {
case "Message":
alert(data.Message);
break;
case "Refresh":
$(".modal-body").html(data); //modify here....
break;
case "RefereshList":
{
hideModal();
const refereshUrl = form.attr("data-refereshurl");
const refereshDiv = form.attr("data-refereshdiv");
get(refereshUrl, refereshDiv);
}
break;
case "setValue":
{
const element = form.data("element");
$(`#${element}`).html(data);
}
break;
default:
}
}
function get(url, refereshDiv) {
const searchModel = window.location.search;
$.get(url,
searchModel,
function (result) {
$("#" + refereshDiv).html(result);
});
}
</script>
}
Partial View does not change anything
#model CustomerCombine
<form asp-page="./Index" asp-page-handler="Customer"
method="get"
data-ajax="true"
data-callback=""
data-action="Refresh"
>
<div class="form-group">
<input asp-for="#Model.MySearchModel.FullName" class="form-control " placeholder="search..." />
</div>
<button class="customer-submit btn btn-success" type="submit">جستجو</button>
</form>
<table>
#foreach (var item in #Model.MyViewModels)
{
<tr>
<td>#item.Id</td>
<td>#item.FullName</td>
<td>#item.Mobile</td>
<td>#item.Email</td>
<td>#item.Address</td>
<td>#item.Image</td>
</tr>
}
</table>
PageModel
public IActionResult OnGetCustomer(CustomerSearchModel MySearchModel)//change here....
{
CustomerCombine combine = new CustomerCombine
{
MyViewModels = _customerApplication.GetAll(searchModel) //be sure here contains value...
};
return Partial("./Customer", combine);
}
Result:

How to send upload file to controller - files is always empty

UserAdmin.cshtml
<div class="modal-body">
<form id="upload-file-dialog-form"
class="needs-validation form-group" novalidate
onsubmit="UploadFile()"
enctype="multipart/form-data"
method="post">
<div class="col-md-10">
<p>Upload one or more files using this form:</p>
<input type="file" name="file_Uploader" />
</div>
<div class="form-group">
<div class="col-md-10 modal-footer">
<input type="submit" class="btn btn-primary" value="Upload"/>
</div>
</div>
</form>
</div>
UserAdmin.js
function UploadFile() {
var form = $('form')[0];
var formData = new FormData(form);
console.log(formData);
$.ajax({
url: '/API/Upload',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function (data) {
},
error: function () {
}
});
}
Controller
[HttpPost]
public async Task<IActionResult> Upload(List<IFileUpload> files)
{
try
{
var check = (HttpContext.Request.Form.Files);
long size = files.Sum(f => f.Length);
//some code removed
return Ok(new { count = files.Count, size, filePaths });
}
catch (Exception exc)
{
logger.Error("Error in upload() " + exc.Message);
throw;
}
}
the files in controller is always 0.
If onsubmit="UploadFile()" is replaced with
asp-controller="API" asp-action="Upload"
then I get something in check but again converting it to List of IFileUpload is another blocker
First of all, If you want to upload multiple files you have to add multiple="multiple" in your input. FormData will be empty if you print it like this, you have to iterate through the items.
<input type="file" name="file_Uploader" multiple="multiple" />
Please follow the codes below, I tested it working.
Complete form
<form id="upload-file-dialog-form"
onsubmit="UploadFile(event)">
<div class="col-md-10">
<p>Upload one or more files using this form:</p>
<input type="file" name="file_Uploader" multiple="multiple" />
</div>
<div class="form-group">
<div class="col-md-10 modal-footer">
<input type="submit" class="btn btn-primary" value="Upload" />
</div>
</div>
</form>
Construct form data like below
<script>
function UploadFile(e) {
e.preventDefault();
var formData = new FormData($('#upload-file-dialog-form')[0]);
$.each($("input[type='file']")[0].files, function(i, file) {
formData.append('files', file);
});
$.ajax({
url: '/API/Upload',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(data) {
},
error: function() {
}
});
}
</script>
Action method
[HttpPost]
public async Task<IActionResult> Upload(List<IFormFile> files)
{
try
{
var check = (HttpContext.Request.Form.Files);
long size = files.Sum(f => f.Length);
return Ok(new { count = files.Count, size });
}
catch (Exception exc)
{
_logger.LogWarning("Error in upload() " + exc.Message);
throw;
}
}
In model class, use IFormFile
public List<IFormFile> file_Uploader {get;set;}"
In controller, change the parameter like this
public async Task<IActionResult> Upload(List<IFormFile> file_Uploader)
add multiple to upload more files, and keep the name attribute the same as parameter to post value, code like below:
<input type="file" name="file_Uploader" multiple/>
result:

How do i send the data to edit boxes on the same page?

i have the following page generated
when i click the Edit link, the record data must be sent to the input boxes on teh same page (without refreshing the page)
currently i have the controller code and views
controller: ProductCategory
public class ProductCategoryController : Controller
{
//
// GET: /ProductCategory/
TUDBEntities _db = new TUDBEntities();
public ActionResult Index(string Code)
{
var categories = _db.mt_ProductCategories
.Where(pc => Code == "" || Code == null|| pc.CatCode == Code)
.Select(
c => new ProductCategory {
Id = c.Id,
CategoryCode = c.CatCode,
Name = c.CatName,
Url = c.Url
});
if (Request.IsAjaxRequest())
{
return PartialView("_ProductCategoryList", categories);
}
return View(categories);
}
[HttpPost]
public ActionResult Save(ProductCategory userData)
{
try
{
if (ModelState.IsValid)
{
mt_ProductCategories cat = new mt_ProductCategories { CatCode = userData.CategoryCode, CatName = userData.Name };
// TODO: Add insert logic here
_db.mt_ProductCategories.Add(cat);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
catch
{
return View();
}
}
public ActionResult Edit(int id)
{
var category = _db.mt_ProductCategories
.Where(pc => pc.Id == id)
.Select(pc => new ProductCategory
{ Id=pc.Id, CategoryCode=pc.CatCode,Name=pc.CatName }).ToList();
return RedirectToAction("Index", category);
}
}
Index view
#model IEnumerable<eComm1.Models.ProductCategory>
#using(Ajax.BeginForm("Save", "ProductCategory",
new AjaxOptions {
HttpMethod="POST",
UpdateTargetId="prod-grid",
InsertionMode=InsertionMode.Replace,
OnSuccess="loaddivdata"
}))
{
<fieldset class="form-group">
<label for="Code">Category Code</label>
<input type="text" class="form-control focus" id="Code" name="CategoryCode" placeholder="Product category code" >
</fieldset>
<fieldset class="form-group">
<label for="ProdName">Product Name</label>
<input type="text" class="form-control" id="ProdName" name="Name" placeholder="Product Name">
</fieldset>
<button type="Submit" class="btn btn-primary">Save</button>
}
<hr />
<div id="prod-grid">
#Html.Partial("_ProductCategoryList", #Model)
</div>
<script type="text/javascript">
$(function () {
$('.focus :input').focus();
});
function loaddivdata() {
$('#prod-grid').html();
$('#Code, #ProdName').val('');
};
// $('#prod-grid').load(function () {
// $.ajax({
// url:'ProductCategoryController/Index',
// method:'GET',
// type:'application/html',
// success: function () { alert('called');}
// });
// });
//});
</script>
Partial View: _ProductCategoryList
#model IEnumerable<eComm1.Models.ProductCategory>
<div class="panel panel-default">
#if (Model.Count() == 0) { <div class="panel-heading">Product Categories - <span style='color:red;font-weight:bold' >0 RESULTS FOUND</span></div>
}else{
<!-- Default panel contents -->
<div class="panel-heading">Product Categories</div>
}
<!-- Table -->
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.CategoryCode)
</th>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Url)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.CategoryCode)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Url)
</td>
<td>
#*#Html.beActionLink("Edit", "Edit", new { id=item.Id }) |
#Html.ActionLink("Details", "Details", new { id=item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id=item.Id })*#
#Ajax.ActionLink("Edit", "Edit", "ProductCategory", new { id=item.Id}, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "", OnSuccess = "loadformdata" }) |
#Ajax.ActionLink("Delete", "Delete", "ProductCategory", new { id=item.Id}, new AjaxOptions{ HttpMethod="POST", UpdateTargetId="", OnSuccess="loadformdata"})
</td>
</tr>
}
</table>
</div>
How do i modify my code to send data those input control and in my code how do i create hidden field for Id value so it can be send to the Edit(collection, int id) action to update the record?
for Stephen Muecke, i have added my jquery files through the bundles
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/ecomm").Include(
"~/Scripts/jquery-{version}.js",
"~/Scripts/jquery-2.1.4.min.js",
"~/Scripts/bootstrap.js",
"~/Scripts/bootstrap.min.js",
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"
));
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
"~/Scripts/jquery-ui-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.min.css",
"~/Content/bootstrap.css",
"~/Content/style.css"));
bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
"~/Content/themes/base/jquery.ui.core.css",
"~/Content/themes/base/jquery.ui.resizable.css",
"~/Content/themes/base/jquery.ui.selectable.css",
"~/Content/themes/base/jquery.ui.accordion.css",
"~/Content/themes/base/jquery.ui.autocomplete.css",
"~/Content/themes/base/jquery.ui.button.css",
"~/Content/themes/base/jquery.ui.dialog.css",
"~/Content/themes/base/jquery.ui.slider.css",
"~/Content/themes/base/jquery.ui.tabs.css",
"~/Content/themes/base/jquery.ui.datepicker.css",
"~/Content/themes/base/jquery.ui.progressbar.css",
"~/Content/themes/base/jquery.ui.theme.css"));
}
In the partial view
#Ajax.ActionLink("Edit", "Edit", "ProductCategory", new { id = item.Id }, new AjaxOptions { HttpMethod = "GET", OnSuccess = "loadformdata" }) |
#Ajax.ActionLink("Delete", "Delete", "ProductCategory", new { id=item.Id}, new AjaxOptions{ HttpMethod="POST", OnSuccess="loadformdata"})
in the index view the following js function:
function loadformdata() {
var cells = $(this).closest('tr').children('td');
alert(cells.eq(0).text());
//$('#Code').val(cells.eq(0).text());
//$('#ProdName').val(cells.eq(1).text());
}
To: Stephen Muecke:
i have removed above loadformdata() and put everything as you said. this youtube video shows the problem that still does not call that click event
To: Steven Meucke:
there's still no luck, for ease i have added a alert() in the function and the alert() won't show. Here is the video
Give you 'Edit' link a class name (say) class="edit" and handle its .click() event to update the form controls
$('.edit').click(function() {
var cells = $(this).closest('tr').children('td');
$('#Code').val(cells.eq(0).text());
$('#ProdName').val(cells.eq(1).text());
return false; // cancel the default redirect
});
Side note: You could just replace the ActionLink() code with Edit and the return false; line is not necessary.
write script for ajax call:
$('#edit').click(function () {
// var data = {here you will pass item.id }
$.ajax({
url:'ProductCategoryController/Edit',
data: {id : data}
method:'GET',
success: function (data) {
//clear html page here
//reload html page by passing 'data' passes in function
//e.g. suppose html page id is 'xyz' then $("#xyz").html(data)
}
});
});

asp.net mvc modal popup

I'm working a simple modal popup.My goal is to send dialog's information to another view.
My index view below.
<button id="modal-opener">Open</button>
<div id="dialog-modal">
#using (Ajax.BeginForm("Index",new AjaxOptions{UpdateTargetId = "ID",HttpMethod = "Post",OnSuccess = "onSuccess"}))
{
<div>
<fieldset>
<legend>Acount Information</legend>
<div id="editor-label">
#Html.LabelFor(a=>a.FirstName)
</div>
<div id="editor-field">
#Html.TextBoxFor(a=>a.FirstName)
#Html.ValidationMessageFor(a=>a.FirstName)
</div>
<div id="editor-label">
#Html.LabelFor(a=>a.LastName)
</div>
<div id="editor-field">
#Html.TextBoxFor(a=>a.LastName)
#Html.ValidationMessageFor(a=>a.LastName)
</div>
<p>
<input type="submit" value="submit"/>
</p>
</fieldset>
</div>
}
</div>
And my _Layout.cshtml is below:
<script>
$(function() {
$("#dialog-modal").dialog({
autoOpen: false,
width: 300,
height: 250,
show: {
effect: "blind",
duration:1000
},
hide: {
effect: "explode",
duration:1000
}
});
$("#modal-opener").click(function() {
$("#dialog-modal").dialog("open");
});
});
function onSuccess() {
$("#dialog-modal").dialog("close");
}
</script>
And my controller is below ,so I want to send FirstName and LastName to details view
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Person person)
{
return RedirectToAction("Details",person);
}
public ActionResult Details(Person person)
{
return View(person);
}
If you want to do full redirect rather than a partial postback, you will need to change this line:
#using (Ajax.BeginForm("Index",new AjaxOptions{UpdateTargetId = "ID",HttpMethod = "Post",OnSuccess = "onSuccess"}))
into
#using(Html.BeginForm("Index"))
If you just want to do the partial postback to the details view, then change the action on the from Index to details
#using (Ajax.BeginForm("Details",new AjaxOptions{UpdateTargetId = "ID",HttpMethod = "Post",OnSuccess = "onSuccess"}))
HTH