MVC3 partial view does not return ajax post - asp.net-mvc-3

The idea of the problem is that i have a "CreateINF" view then i display a pop up with that calls a partial view. In this pop up there is a grid, then when i select one of the elements of this grid i want to fill some textbox on the "CreateINF" view with the information of the element selected in the popup but this last action does not work and I dont know where is the error
this is the pop up "PopTrabajador"
#model PagedList.IPagedList<Sistema_GEC_v3.Models.TrabajadorExterno>
#{
ViewBag.Title = "Buscar Reserva";
}
<h1><strong>Resultado Búsqueda</strong></h1>
<br />
<table id="MainContent_Table2" rules="all" style="border-color: Black; width: 900px; margin-bottom: 0px;" border="1">
<tr>
<th style="font-weight: bold; width: 150px;" align="center">
</th>
<th style="font-weight: bold; width: 150px;" align="center">
#Html.LabelFor(modelItem => Model.First().vcNombre)
</th>
<th style="font-weight: bold; width: 150px;" align="center">
#Html.LabelFor(modelItem => Model.First().vcApellidoPaterno)
</th>
<th style="font-weight: bold; width: 150px;" align="center">
#Html.LabelFor(modelItem => Model.First().vcApellidoMaterno)
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td align="center">
#using (Ajax.BeginForm("DevolverTrabajador", "Infracciones",
null
, new AjaxOptions
{
UpdateTargetId = "update-message",
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
OnSuccess = "searchSuccess"
}, new { #id = "searchForm"+#item.idTrabajadorExterno}))
{
<div id="update-message" class="error invisible"></div>
<input data-val="true" data-val-number="The field idTrabajadorExterno must be a number." data-val-required="El campo idTrabajadorExterno es obligatorio." id="idTrabajadorExterno" name="idTrabajadorExterno" type="hidden" value="#item.idTrabajadorExterno" />
#Html.HiddenFor(model => item.idTrabajadorExterno, new { id = "idTrabajadorExterno" + #item.idTrabajadorExterno })
#Html.HiddenFor(model => item.vcNombre, new { id = "vcNombre" + #item.idTrabajadorExterno })
<input type="submit" value="Seleccionar" />
}
</td>
<td style="font-weight: normal; width: 150px;" align="center">
#Html.DisplayFor(modelItem => item.vcNombre)
</td>
<td style="font-weight: normal; width: 150px;" align="center">
#Html.DisplayFor(modelItem => item.vcApellidoPaterno)
</td>
<td style="font-weight: normal; width: 150px;" align="center">
#Html.DisplayFor(modelItem => item.vcApellidoMaterno)
</td>
</tr>
}
</table>
this is the view "CreateINF"
#model Sistema_GEC_v3.Models.Infraccion
#{
ViewBag.Title = "Create";
}
<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>
<link href="#Url.Content("~/Content/themes/base/jquery.ui.all.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script>
<script type="text/javascript">
var linkObj;
//$(document).ready(function () {
$(function () {
$(".busqueda").button();
$('#dialog').dialog({
autoOpen: false,
width: 930,
resizable: false,
title: 'hi there',
modal: true
});
$(".busqueda").click(function () {
linkObj = $(this);
var dialogDiv = $('#dialog');
var viewUrl = linkObj.attr('href');
$.get(viewUrl, function (data) {
dialogDiv.html(data);
dialogDiv.dialog('open');
});
return false;
});
});
function searchSuccess() {
var id = $("#update-message").html();
var parent = linkObj.closest("tr");
document.getElementById('tipoTrabajador').value = $("#vcNombre" + id.toString()).val();
$('#dialog').dialog('close');
}
function actualizarVentanaModal(viewUrl) {
var dialogDiv = $('#dialog');
$.get(viewUrl, function (data) {
dialogDiv.html(data);
});
}
// });
</script>
<div id="commonMessage"></div>
<div id="dialog" title="Seleccionar Cliente"></div>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Infraccion</legend>
<div class="editor-label">
#Html.LabelFor(model => model.vcCodigoInfraccion)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.vcCodigoInfraccion, new { id = "tipoTrabajador" })
#Html.ValidationMessageFor(model => model.vcCodigoInfraccion)
</div>
<a class="busqueda" href= "#Href("~/Infracciones/PopTrabajador")"> <img src="#Href("~/Content/Images/buscar.png")" alt="0" title="Buscar" id="" border="0" height="16" width="16"/></a>
</fieldset>
<p>
<input value="Guardar" type="submit" name = "button"/>
</p>
}
And this is the controller
public ActionResult PopTrabajador(int? page, string tipoTrabajador)
{
int tamPag = 10;
int numPag = page ?? 1;
var trabajadoresE = dbTExterno.trabajadoresExternos.OrderBy(t => t.vcNombre);
return PartialView("PopTrabajador", trabajadoresE.ToPagedList(numPag, tamPag));
}
[HttpPost]
public ActionResult DevolverTrabajador(TrabajadorExterno trabajador)
{
try
{
return Content(trabajador.idTrabajadorExterno.ToString());
}
catch (Exception e)
{
return RedirectToAction("General", "Error");
}
}
public ActionResult CreateINF()
{
return View();
}
//
// POST: /Infracciones/Create
[HttpPost]
public ActionResult CreateINF(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}

Related

Unable to get updated Checkboxes from uploaded Excel file in asp.net core 3.1 mvc

As soon as the Excel file is uploaded and clicked on Submit button, the data in the Excel file will be populated as shown in the below screenshot. Some checkboxes will be selected while some others are not, based on the conditions written in the program. Till here everything is working fine.
End user selects/un-selects checkboxes, and clicks on Process Hold Reasons button. Now, I want updated model with modified checkboxes values. I'm not even understanding how and where to write the code to achieve this. Tried number of ways, but unable to succeed.
Can someone please suggest me on this!
Below is the code in Index.cshtml page.
#model SupportTool.Models.ViewModels.EligibilityIssuesViewModel
#{
ViewData["Title"] = "Eligiblity Issues";
}
<style>
.Success {
font-weight: bold;
color: green;
font-size: 15px;
}
.Error {
font-weight: bold;
color: red;
font-size: 15px;
}
td {
height: 20px;
}
</style>
<br />
<br />
<div>
<span class="Success">#ViewBag.Success</span>
<span class="Error">#ViewBag.Error</span>
</div>
<form asp-controller="EligibilityIssues" asp-action="Index" method="post" class="form-horizontal" role="form" enctype="multipart/form-data">
<div class="form-group">
<div class="row">
<div class="alert-danger" asp-validation-summary="ModelOnly"></div>
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<p>Upload Excel file:</p>
<div class="custom-file">
<input asp-for="ExportedExcelFile" class="form-control custom-file-input" />
<label class="custom-file-label">Choose file...</label>
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input type="submit" value="Submit" class="btn-success" />
</div>
</div>
</div>
#section Scripts {
<script>
$(function () {
$('.custom-file-input').on('change', function () {
var fileName = $(this).val().split('\\').pop();
$(this).next('.custom-file-label').html(fileName);
});
});
</script>
}
#if (Model != null && Model.HoldReasons != null)
{
<h1>Eligibility issues should be shown here</h1>
<table>
<thead>
<tr>
<th> </th>
<th>Hold Reasons</th>
</tr>
</thead>
<tbody>
#for (int i = 0; i < Model.HoldReasons.Count; i++)
{
<tr>
<td>
#Html.CheckBox("holdReason[" + i + "].HoldReasonShouldBeChecked", Model.HoldReasons[i].HoldReasonShouldBeChecked)
#if (!Model.HoldReasons[i].HoldReasonShouldBeChecked)
{
<span style="border: 1px solid red">
(#Model.HoldReasons[i].StateName)#Model.HoldReasons[i].HoldReason
</span>
}
else
{
<span>(#Model.HoldReasons[i].StateName)#Model.HoldReasons[i].HoldReason</span>
}
#Html.Hidden("holdReason[" + i + "].WorkOrderId", Model.HoldReasons[i].WorkOrderId)
</td>
</tr>
}
</tbody>
</table>
<input type="submit" asp-action="ProcessHoldReasons" value="Process Hold Reasons" class="btn btn-primary" />
}
</form>
Below is the Code in HomeController
namespace SupportTool.Controllers
{
public class EligibilityIssuesController : Controller
{
private readonly IEligibilityIssuesBLL _bll;
private readonly IWebHostEnvironment _hostEnvironment;
public EligibilityIssuesController(IEligibilityIssuesBLL bll, IWebHostEnvironment hostEnvironment)
{
_bll = bll ?? throw new ArgumentNullException(nameof(bll));
_hostEnvironment = hostEnvironment ?? throw new ArgumentNullException(nameof(hostEnvironment));
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(EligibilityIssuesViewModel model)
{
try
{
if (ModelState.IsValid)
{
if (model.ExportedExcelFile != null)
{
var folder = Path.Combine(_hostEnvironment.WebRootPath, "uploaded_excel_files");
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
var incomingFileName = model.ExportedExcelFile.FileName;
model.UploadedExcelFileName = Path.Combine(folder, incomingFileName);
using (var fileStream = new FileStream(model.UploadedExcelFileName, FileMode.Create))
{
model.ExportedExcelFile.CopyTo(fileStream);
}
model.HoldReasons = _bll.GetHoldReasons(model);
}
return View(model);
}
return View(model);
}
catch (Exception ex)
{
ViewBag.Error = new HtmlString(#"Unexpected error occurred. Below is the message for your verification:<br />"
+ ex.Message);
return View(model);
}
}
}
}

How can we use Web API through HttpClient?

I have used .NET API to consume it. But the code is not working. Can you please give me solution for the below code?
// State object
List<SelectListItem> state = new List<SelectListItem>();
// Client
HttpClient client1 = new HttpClient();
client1.BaseAddress = new Uri("http://localhost:2585/");
// JSON type
client1.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json")
);
// Web API controller
var response1 = client1.GetAsync("api/State");
if (response1.IsSuccessStatusCode) // Response type
{
state = JsonConvert.DeserializeObject<List<SelectListItem>>(response1.Content.ReadAsStringAsync().Result);
return Json(state, JsonRequestBehavior.AllowGet);
[HttpGet]
public ActionResult Index()
{
List<Student> EmpInfo = new List<Student>();
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:2585/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync("api/StudentApi").Result;
if (response.IsSuccessStatusCode)
{
EmpInfo = JsonConvert.DeserializeObject<List<Student>>(response.Content.ReadAsStringAsync().Result);
return View(EmpInfo);
}
return View();
}
[HttpGet]
public PartialViewResult Edit(int id)
{
StudentViewModel EmpInfo = new StudentViewModel();
HttpClient client1 = new HttpClient();
client1.BaseAddress = new Uri("http://localhost:2585/");
client1.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var responsecountry = client1.GetAsync("api/Country/").Result;
List<SelectListItem> country = new List<SelectListItem>();
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:2585/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync("api/StudentApi/" + id).Result;
if (response.IsSuccessStatusCode)
{
EmpInfo = JsonConvert.DeserializeObject<StudentViewModel>(response.Content.ReadAsStringAsync().Result);
if (responsecountry.IsSuccessStatusCode)
{
country = JsonConvert.DeserializeObject<List<SelectListItem>>(responsecountry.Content.ReadAsStringAsync().Result);
EmpInfo.Country = country;
}
return PartialView(EmpInfo);
}
return PartialView();
}
public ActionResult Create()
{
StudentViewModel student = new StudentViewModel();
List<SelectListItem> country = new List<SelectListItem>();
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:2585/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync("api/Country/").Result;
List<SelectListItem> state = new List<SelectListItem>();
HttpClient client1 = new HttpClient();
client1.BaseAddress = new Uri("http://localhost:2585/");
client1.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
if (response.IsSuccessStatusCode)
{
country = JsonConvert.DeserializeObject<List<SelectListItem>>(response.Content.ReadAsStringAsync().Result);
student.Country = country;
var response1 = client1.GetAsync("api/State/" + Convert.ToInt32(country.FirstOrDefault().Value)).Result;
if (response1.IsSuccessStatusCode)
{
state = JsonConvert.DeserializeObject<List<SelectListItem>>(response1.Content.ReadAsStringAsync().Result);
student.State = state;
}
}
return View(student);
}
public JsonResult GetStates(int countryId)
{
List<SelectListItem> state = new List<SelectListItem>();
HttpClient client1 = new HttpClient();
client1.BaseAddress = new Uri("http://localhost:2585/");
client1.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response1 = client1.GetAsync("api/State/" + countryId).Result;
if (response1.IsSuccessStatusCode)
{
state = JsonConvert.DeserializeObject<List<SelectListItem>>(response1.Content.ReadAsStringAsync().Result);
return Json(state, JsonRequestBehavior.AllowGet);
}
return Json(state);
}
[HttpPost]
public ActionResult Create(Student student)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:2585/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PostAsJsonAsync("api/StudentApi", student).Result;
if (response.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
return null;
}
[HttpPost]
public ActionResult Update(StudentViewModel student)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:2585/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var stu = new Student()
{
Id = student.Id,
FirstName = student.FirstName,
LastName = student.LastName,
DateOfBirth = student.DateOfBirth,
Email = student.Email,
Phone = student.Phone,
CountryId = student.CountryId
};
HttpResponseMessage response = client.PutAsJsonAsync("api/StudentApi/", stu).Result;
if (response.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
return null;
}
[HttpPost]
public JsonResult EmailExists(string email)
{
return Json(!String.Equals(email, "h#h.com", StringComparison.OrdinalIgnoreCase));
//var user = Membership.GetUser(UserName);
//return Json(user == null);
}
}
-----------
Create
-----------
#model Practice.Web.Models.StudentViewModel
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>SignUp</title>
<script src="#Url.Content("~/Scripts/jquery-1.12.4.js")"></script>
<script type="text/javascript">
$(document).ready(function () {
//Dropdownlist Selectedchange event
$("#CountryId").change(function () {
$("#StateId").empty();
$.ajax({
type: 'GET',
url: '#Url.Action("GetStates")', // we are calling json method
dataType: 'json',
data: { countryId: $("#CountryId").val() },
success: function (state) {
//debugger;
$.each(state, function (i, s) {
$("#StateId").append('<option value="' + s.Value + '">' +
s.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
</head>
<body>
#using (Html.BeginForm("Create", "Student", FormMethod.Post))
{
<table cellpadding="0" cellspacing="0">
<tr>
<th colspan="2" align="center">Person Details</th>
</tr>
<tr>
<td>First Name: </td>
<td>
#Html.TextBoxFor(m => m.FirstName)
</td>
</tr>
<tr>
<td>Last Name: </td>
<td>
#Html.TextBoxFor(m => m.LastName)
</td>
</tr>
<tr>
<td>Date Of Birth: </td>
<td>
#Html.TextBoxFor(m => m.DateOfBirth)
</td>
</tr>
<tr>
<td>Email: </td>
<td>
#Html.TextBoxFor(m => m.Email)
#Html.ValidationMessageFor(model => model.Email)
</td>
</tr>
<tr>
<td>Phone: </td>
<td>
#Html.TextBoxFor(m => m.Phone)
</td>
</tr>
<tr>
<td>Country: </td>
<td>
#Html.DropDownListFor(m => m.CountryId, Model.Country)
</td>
</tr>
<tr>
<td>State: </td>
<td>
#Html.DropDownListFor(m => m.StateId, Model.State)
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
}
</body>
</html>
-----------------
Edit
---------------------
#model Practice.Web.Models.StudentViewModel
#{
ViewBag.Title = "Edit";
}
<style>
.button {
background-color: #4CAF50; /* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
.button1 {
border-radius: 2px;
}
.button2 {
border-radius: 4px;
}
.button3 {
border-radius: 8px;
}
.button4 {
border-radius: 12px;
}
.button5 {
border-radius: 50%;
}
</style>
<div class="modal-body">
#using (Ajax.BeginForm("Update", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "divEmp" }))
{
<table cellpadding="0" cellspacing="0">
<tr>
<th colspan="2" align="center">Person Details</th>
#Html.HiddenFor(m => m.Id)
</tr>
<tr>
<td>First Name: </td>
<td>
#Html.TextBoxFor(m => m.FirstName)
</td>
</tr>
<tr>
<td>Last Name: </td>
<td>
#Html.TextBoxFor(m => m.LastName)
</td>
</tr>
<tr>
<td>Date Of Birth: </td>
<td>
#Html.TextBoxFor(m => m.DateOfBirth)
</td>
</tr>
<tr>
<td>Email: </td>
<td>
#Html.TextBoxFor(m => m.Email)
#Html.ValidationMessageFor(model => model.Email)
</td>
</tr>
<tr>
<td>Phone: </td>
<td>
#Html.TextBoxFor(m => m.Phone)
</td>
</tr>
<tr>
<td>Country: </td>
<td>
#Html.DropDownListFor(m => m.CountryId, Model.Country, new SelectListItem { Value = Model.CountryId.ToString() })
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" id="btnHideModal" /></td>
</tr>
</table>
}
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary button button4">Update</button>
<button type="button" class="btn btn-primary button button4">
Hide
</button>
</div>
<script type="text/javascript">
$(document).ready(function () {
//$("#btnShowModal").click(function () {
$("#loginModal").modal('show');
//});
$("#btnHideModal").click(function () {
$("#loginModal").modal('hide');
});
});
</script>
----------------------
Edit
---------------------
#model IEnumerable<Practice.Entity.Student>
#{
ViewBag.Title = "Index";
}
<html>
<head>
<script src="~/Scripts/jquery-1.12.4.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
#*<script src="#Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.20.min.js")" type="text/javascript"></script>
<link href="#Url.Content("~/Content/themes/base/jquery-ui.min.css") rel=" stylesheet" type="text/css" />
<script>
$(document).ready(function () {
//$(".editDialog").live("click", function (e) {
$(".editDialog").click(function (e) {
debugger;
var url = $(this).attr('href');
$("#dialog-edit").dialog({
title: 'Edit Employee Detail',
autoOpen: false,
resizable: false,
height: 455,
width: 550,
show: { effect: 'drop', direction: "up" },
modal: true,
draggable: true,
open: function (event, ui) {
debugger;
$(this).load(url);
},
close: function (event, ui) {
$(this).dialog('close');
}
});
$("#dialog-edit").dialog('open');
return false;
});
});
</script>*#
</head>
<body id="divEmp">
<h2>Index</h2>
#Html.ActionLink("Create Student", "Create", "Student")
<div id="dialog-edit">
</div>
<table>
<tr>
<td>First Name</td>
<td>Last Name</td>
<td>DOB</td>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#item.FirstName</td>
<td>#item.LastName</td>
<td>#item.DateOfBirth</td>
<td>
#*#Html.ActionLink("Edit", "Edit", new { id = #item.Id }, new { #class = "editDialog" })*#
<a class="editDialog">Edit</a>
</td>
</tr>
}
</table>
<div class="modal fade" tabindex="-1" id="loginModal"
data-keyboard="false" data-backdrop="static">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
×
</button>
<h4 class="modal-title">Satya Login</h4>
<div id="divHtml"></div>
</div>
</div>
</div>
</div>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".editDialog").click(function () {
$("#loginModal").modal('show');
$.ajax({
url: '/Student/Edit/1',
contentType: 'application/html; charset=utf-8',
type: 'GET'
})
.success(function (result) {
$('#divHtml').html(result);
})
.error(function (xhr, status) {
alert(status);
});
});
$("#btnHideModal").click(function () {
$("#loginModal").modal('hide');
});
});
</script>

Get database record using AJAX, Knockout and JSON

I am fairly new to Knockout and Entity Framework and I have a problem where I cannot seem to output any JSON from an MVC 4 controller action via an AJAX call using Knockout onto an html page.
The table includes fields Email and RegsitrationNumber, these are used to validate the user.
If the user exists in the table then their country is displayed on the screen.
The profiler states a Status Code of 200 i.e OK. Can anyone help?
HTML ------
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="./Scripts/jquery-1.8.2.min.js"></script>
</head>
<body>
<div>
<div>
<h2 id="title">Login</h2>
</div>
<div>
<label for="email">Email</label>
<input data-bind="value: $root.Email" type="text" title="Email" />
</div>
<div>
<label for="registrationnumber">Registration Number</label>
<input data-bind="value: $root.RegistrationNumber" type="text" title="RegistrationNumber" />
</div>
<div>
<button data-bind="click: $root.login">Login</button>
</div>
</div>
<table id="products1" data-bind="visible: User().length > 0">
<thead>
<tr>
<th>Country</th>
</tr>
</thead>
<tbody data-bind="foreach: Users">
<tr>
<td data-bind="text: Country"></td>
</tr>
</tbody>
</table>
<script src="./Scripts/knockout-2.2.0.js"></script>
<script src="./Scripts/knockout-2.2.0.debug.js"></script>
<script src="./Scripts/functions.js"></script>
</body>
</html>
JAVASCRIPT -----
function UserViewModel() {
//Make the self as 'this' reference
var self = this;
//Declare observable which will be bind with UI
self.Name = ko.observable("Robbie");
self.Email = ko.observable("rob#test.com");
self.Occupation = ko.observable("Designer");
self.Country = ko.observable("UK");
self.RegistrationNumber = ko.observable("R009");
self.UserDate = ko.observable("06-04-2014");
var User = {
Name: self.Name,
Email: self.Email,
Occupation: self.Occupation,
Country: self.Country,
RegistrationNumber: self.RegistrationNumber,
UserDate: self.UserDate
};
self.User = ko.observable(); //user
self.Users = ko.observableArray(); // list of users
//Login
self.login = function ()
{
alert("login");
if (User.Email() != "" && User.RegistrationNumber() != "") {
$.ajax({
url: '/Admin/Login',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(User),
success: function (data) {
self.Users.push(data);
$('#title').html(data.Email);
}
}).fail(
function (xhr, textStatus, err) {
console.log('fail');
console.log(xhr.statusText);
console.log(textStatus);
console.log(err);
});
} else {
alert('Please enter an email and registration number');
}
};
}
var viewModel = new UserViewModel();
ko.applyBindings(viewModel);
ACTION -----
public ActionResult Login(string Email, string RegistrationNumber)
{
var user = from s in db.Users
select s;
user = user.Where(s => s.Email.ToUpper().Equals(Email.ToUpper())
&& s.RegistrationNumber.ToUpper().Equals(RegistrationNumber.ToUpper())
);
if (user == null)
{
return HttpNotFound();
}
return Json(user, JsonRequestBehavior.AllowGet);
}
Looks like your binding is incorrect...
<table id="products1" data-bind="visible: Users().length > 0">
<thead>
<tr>
<th>Country</th>
</tr>
</thead>
<tbody data-bind="foreach: Users">
<tr>
<td data-bind="text: Country"></td>
</tr>
</tbody>
</table>
User().length should be Users().length.

why ajax.actionlink not refresh the page?

First,sorry to my bad english.
I don't understand why my page not refresh when i click on the delete user...
After the click i check in database and the user is delete but my page with table not refresh, i dont't understand.
My views is:
#model IEnumerable<SiteWebEmpty.Models.User.UserDisplay>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcAjax.debug.js")" type="text/javascript"></script>
<h2>Display User</h2>
<div id="deleteUser">
#using (Html.BeginForm())
{
<table class="tabledisplayUser" border="1">
<tr>
<th>Name FirstName</th>
<th>UserName</th>
<th>Roles</th>
<th>Choice</th>
</tr>
<tr>
<th>#Html.Editor("name")</th>
<th>#Html.Editor("username")</th>
<th>#Html.Editor("roles")</th>
<th>#Html.Editor("choice")</th>
</tr>
#foreach (var user in Model)
{
<tr>
<td class="action nameFirstName">#Html.DisplayFor(u => user.NameFirstName)</td>
<td class="action userName">#Html.DisplayFor(u => user.UserName)</td>
#if (user.Roles.Roles.Count.Equals(0))
{
<td>Nobody Role</td>
}
else
{
<td>#Html.DropDownList("Roles", user.Roles.Roles)</td>
}
<td>#Html.ActionLink("Edit", "Edit", new { UserName = user.UserName }) | #Ajax.ActionLink("Delete", "Delete", new { UserName = user.UserName },
new AjaxOptions()
{
HttpMethod = "POST",
Confirm = "Do you want delete this user?",
UpdateTargetId = "deleteUser"
})</td>
</tr>
}
</table>
}
</div>
My controller is:
public ActionResult DisplayUser()
{
List<UserDisplay> users=getAllUserInDB();
GetAllNameFirstNameLDAP(users);
return View(users);
}
public ActionResult Delete(String userName)
{
DeleteDB(userName);
if (!Request.IsAjaxRequest())
return RedirectToAction("DisplayUser");
else
{
List<UserDisplay> users = getAllUserInDB();
GetAllNameFirstNameLDAP(users);
return PartialView("DisplayUser",users);
}
}
I don't understand why it not working, thank you for your help !
UpdateTargetId = "deleteUser" means to refresh a DOM element with id="deleteUser". You don't have such element.
You have:
<div class="deleteUser">
which is not the same as:
<div id="deleteUser">
So replace the class with id and your table should refresh normally.

Edit button in a view details popup in MVC 3 using jQuery

I am currently in the process of setting up an MVC entities page with the ability to list all entities of a certain type, using jQuery popups to create new entities, edit or delete existing entities.
As not all entities' details are shown in the list, I would like to provide a details view (read only) which has an edit button in case changes need to be made.
However, at the moment I have not been able to implement this and would welcome any suggestions on how to proceed. Please find the view definitions included below:
Entity Country:
/Views/Country/Index:
#model IEnumerable<MVCjQuerySample2.Entities.Country>
#{
ViewBag.Title = "Countries";
}
<h2>Countries</h2>
<span class="AddLink IconLink"><img src="/Content/Images/Create.png" alt="Add new country" /></span>
<div id="ListBlock"></div>
<div id="EditDialog" title="" class="Hidden"></div>
<div id="DeleteDialog" title="" class="Hidden"></div>
<script type="text/javascript">
$(function () {
$("#EditDialog").dialog({
autoOpen: false, width: 400, height: 330, modal: true,
buttons: {
"Save": function () {
if ($("#EditForm").validate().form()) {
$.post("/Country/Save", $("#EditForm").serialize(), function (data) {
$("#EditDialog").dialog("close");
$("#ListBlock").html(data);
});
}
},
Cancel: function () { $(this).dialog("close"); }
}
});
$("#DeleteDialog").dialog({
autoOpen: false, width: 400, height: 330, modal: true,
buttons: {
"Delete": function () {
$.post("/Country/Delete", $("#DeleteForm").serialize(), function (data) {
$("#DeleteDialog").dialog("close");
$("#ListBlock").html(data);
});
},
Cancel: function () { $(this).dialog("close"); }
}
});
$(".AddLink").click(function () {
$("#EditDialog").html("")
.dialog("option", "title", "Add new Country")
.load("/Country/Create", function () { $("#EditDialog").dialog("open"); });
});
$(".EditLink").live("click", function () {
var id = $(this).attr("itemid");
$("#EditDialog").html("")
.dialog("option", "title", "Edit Country")
.load("/Country/Edit/" + id, function () { $("#EditDialog").dialog("open"); });
});
$(".DeleteLink").live("click", function () {
var id = $(this).attr("itemid");
$("#DeleteDialog").html("")
.dialog("option", "title", "Delete Country")
.load("/Country/DeleteConfirm/" + id, function () { $("#DeleteDialog").dialog("open"); });
});
LoadList();
});
function LoadList() {
$("#ListBlock").load("/Country/List");
}
/Views/Country/List:#using MVCjQuerySample2.Helpers
#model IEnumerable<MVCjQuerySample2.Entities.Country>
<table class="CountryList">
<tr>
<th>Iso</th>
<th>Name</th>
<th>Edit</th>
<th>Delete</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Iso)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
<span class="EditLink IconLink" itemid="#item.Id"><img src="/Content/Images/Pencil.png" alt="Edit" /></span>
<!--#Html.ImageActionLink(#"\Content\Images\Pencil.png", "Edit", "Edit", new { id = item.Id })-->
</td>
<td>
<span class="DeleteLink IconLink" itemid="#item.Id"><img src="/Content/Images/Delete.png" alt="Delete" /></span>
<!--#Html.ImageActionLink(#"\Content\Images\Delete.png", "Delete", "Delete", new { id = item.Id })-->
</td>
</tr>
}
</table>
/Views/Country/EditForm:
#model MVCjQuerySample2.Entities.Country
#using (Html.BeginForm("Save", "Country", FormMethod.Post, new { id = "EditForm" }))
{
#Html.Hidden("Id")
#Html.Hidden("CreatedBy")
#Html.Hidden("CreatedOn")
#Html.Hidden("UpdatedBy")
#Html.Hidden("UpdatedOn")
<table>
<tr>
<td>Iso</td>
<td>#Html.TextBox("Iso")</td>
</tr>
<tr>
<td>Name</td>
<td>#Html.TextBox("Name")</td>
</tr>
<tr>
<td>Created by</td>
<td>#Html.DisplayText("CreatedBy")</td>
</tr>
<tr>
<td>Created on</td>
<td>#Html.DisplayText("CreatedOn")</td>
</tr>
<tr>
<td>Updated by</td>
<td>#Html.DisplayText("UpdatedBy")</td>
</tr>
<tr>
<td>Updated on</td>
<td>#Html.DisplayText("UpdatedOn")</td>
</tr>
</table>
}
<script type="text/javascript">
$(function () {
$("#EditForm").validate({
rules: {
Iso: { required: true },
Name: { required: true }
}
});
});
/Views/Country/DeleteConfirm:
#model MVCjQuerySample2.Entities.Country
#using (Html.BeginForm("Delete", "Country", FormMethod.Post, new { id = "DeleteForm" }))
{
#Html.Hidden("Id")
#Html.Hidden("Iso")
#Html.Hidden("Name")
#Html.Hidden("CreatedOn")
#Html.Hidden("CreatedBy")
#Html.Hidden("UpdatedOn")
#Html.Hidden("UpdatedBy")
<table>
<tr>
<td>Iso</td>
<td>#Html.DisplayText("Iso")</td>
</tr>
<tr>
<td>Name</td>
<td>#Html.DisplayText("Name")</td>
</tr>
<tr>
<td>Created by</td>
<td>#Html.DisplayText("CreatedBy")</td>
</tr>
<tr>
<td>Created on</td>
<td>#Html.DisplayText("CreatedOn")</td>
</tr>
<tr>
<td>Updated by</td>
<td>#Html.DisplayText("UpdatedBy")</td>
</tr>
<tr>
<td>Updated on</td>
<td>#Html.DisplayText("UpdatedOn")</td>
</tr>
</table>
}

Resources