Partial View not updating the razor value - c#

I have a main page:
#model List<NovoRelatorioWeb.Controllers.HomeController.Campo>
#{
ViewBag.Title = "Relatorio";
}
<div id="RelatorioTablet">
<div class="container">
<div class="row">
<div class="col-lg-8">
<div class="row">
<div class="col-sm-12">
#if (Model != null)
{
<span>
Relatório ELO > Versão 2.0 > #Model[0].Relatorio
</span>
}
</div>
</div>
<hr style="border: 1px solid orangered" />
<div class="row">
<div class="col-sm-2">
<br />
<input type="button" id="butSalvar" class="form-control" style="background-color:orangered" value="Salvar" />
</div>
</div>
<hr style="border: 1px solid orangered" />
</div>
<div class="col-lg-4">
<div>
#Html.Partial("~/Views/Home/PhonePreview.cshtml", Model)
</div>
</div>
</div>
</div>
</div>
#section scripts {
<script src="~/Scripts/relatorio_elo.js" type="text/javascript"></script>
}
and it calls another page:
#model List<NovoRelatorioWeb.Controllers.HomeController.Campo>
#{
Layout = null;
}
<div>
<div id="PhonePreview" style="border:1px solid black;font-size:20px;">
#if (Model != null)
{
<div class="container1" style="background-color:orangered;padding-top:5px;padding-bottom:5px;">
<div class="row" style="text-align:center;width:100%;">
<div class="col-sm-12" >
<span style="color:white;">
#ViewBag.Relatorio
</span>
</div>
</div>
</div>
foreach (var campo in Model)
{
if (campo.Tipo == "Text")
{
#Html.Partial("~/Views/Home/Controles/Text.cshtml", campo)
}
}
}
</div>
</div>
<style>
input[type=date]::-webkit-inner-spin-button {
-webkit-appearance: none;
display: none;
}
</style>
and it calls
#model NovoRelatorioWeb.Controllers.HomeController.Campo
<div class="1" style="padding-top:5px;padding-bottom:5px;">
<div class="row">
<div class="col-sm-5">
<span style="padding-left:5px;">
#Model.Nome:
</span>
</div>
<div class="col-sm-7" style="text-align:right;">
<input type="text" style="width:100%;" />
</div>
</div>
</div>
and im calling the controller via jquery ajax
var urlService = "/Home/Salvar";
var jsonobj = CriaArrayCampos();
jsonobj = JSON.stringify(jsonobj)
$.ajax({
url: urlService,
type: 'POST',
data: jsonobj,
datatype: 'json',
contentType: 'application/json',
beforeSend: function () {
},
complete: function () {
}
});
It means, a page who calls a partial view, and a partial view inside. OIk, everything works, but when i click save button, i call the controller, who returns a list with objects to update the partial view (i only update the name).. But dont update.. but im making with razor... I have tested and the values comes to the partial view... how can i achieve this?
thanks so much!
Rafael

Related

How to trigger Model Validation inside modal? .NET 5

i Have problem when i try the model validation by trying to fill the form by false.
And when i try to submit with the wrong value (not valid by model validator) it redirects to the page (without model).
Here's the screenshot :
Customer Index
redirect to Customer Create Page when i submit
Here's the code
CONTROLLER
//POST CREATE
[HttpPost]
[AutoValidateAntiforgeryToken]
public IActionResult Create(Models.Customer obj)
{
if (ModelState.IsValid)
{
_db.Customers.Add(obj);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(obj);
}
//GET DELETE
public IActionResult Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var obj = _db.Customers.Find(id);
if (obj == null)
{
return NotFound();
}
return PartialView(obj);
}
Model
public class Customer
{
[Key]
public int Id { get; set; }
[DisplayName("Nama Customer")]
[Required]
[MaxLength(81, ErrorMessage ="Tidak boleh melebihi 81 Karakter")]
public string Nama { get; set; }
public string Alamat { get; set; }
[Phone]
[Required]
public string Telp { get; set; }
}
Index.HTML Button Create
<button id="btnAddCustomer" class="btn btn-primary">Tambah Customer</button>
JS
#section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$("#btnAddCustomer").on("click", function (e) {
var $buttonClicked = $(this);
//var id = $buttonClicked.attr('data-id');
var options = { "backdrop": "static", keyboard: true };
$.ajax({
type: "GET",
url: '#Url.Action("Create", "Customer")',
contentType: "application/json; charset=utf-8",
data: null,
datatype: "json",
success: function (data) {
$('#modalBody').html(data);
$('#modalCustomer').modal(options);
$('#modalCustomer').modal('show');
},
error: function () {
alert("Dynamic content load failed.");
}
});
})
});
CREATE CSHTML
<form method="post" asp-action="Create">
<div class="border p-3">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group row">
<div class="col-4">
</div>
<div class="col-4">
<h2 class="text-black-50 pl-3">Add Customer</h2>
</div>
<div class="col-4">
</div>
</div>
<div class="row">
<div class="col-12 form-horizontal">
<div class="form-group row">
<div class="col-12 form-group">
<label asp-for="Nama"></label>
<input asp-for="Nama" class="form-control" />
<span asp-validation-for="Nama" class="text-danger"></span>
</div>
<br />
<div class="col-12 form-group">
<label asp-for="Telp"></label>
<input asp-for="Telp" class="form-control" />
<span asp-validation-for="Telp" class="text-danger"></span>
</div>
<br />
<div class="col-12 form-group">
<label asp-for="Alamat"></label>
<input type="text" asp-for="Alamat" class="form-control" />
#*validasi form*#
<span asp-validation-for="Alamat" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<div class="col-6">
</div>
<div class="col-6">
</div>
<div class="col-6">
</div>
</div>
<div class="form-group row">
<div class="col-8 offset-2 row">
<div class="col">
<input type="submit" class="btn btn-info w-75" value="create" />
</div>
<div class="col">
<a asp-action="Index" class="btn btn-danger w-75">Back</a>
</div>
</div>
</div>
</div>
</div>
</div>
Thank you (:
And when i try to submit with the wrong value (not valid by model
validator) it redirects to the page (without model).
You use return View(obj); when modelstate is not valid. So it will return view with model and the view name should be the action name(Create) if you do not specific view name. So this result is correct by using your code.
Here is a working demo:
Index.cshtml:
<button id="btnAddCustomer" class="btn btn-primary"> Tambah Customer</button>
<div class="modal fade" id="modalCustomer" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="modalBody">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
#section Scripts{
<script>
$(document).ready(function () {
$("#btnAddCustomer").on("click", function (e) {
var $buttonClicked = $(this);
//var id = $buttonClicked.attr('data-id');
var options = { "backdrop": "static", keyboard: true };
$.ajax({
type: "GET",
url: '#Url.Action("Create", "Customer")',
contentType: "application/json; charset=utf-8",
data: null,
datatype: "json",
success: function (data) {
$('#modalBody').html(data);
//$('#modalCustomer').modal(options);
$('#modalCustomer').modal('show');
},
error: function () {
alert("Dynamic content load failed.");
}
});
})
});
</script>
}
Create.cshtml:
#model Customer
#{
Layout = null; //be sure add this...
}
<form method="post" asp-action="Create">
<div class="border p-3">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group row"><div class="col-4"></div><div class="col-4"><h2 class="text-black-50 pl-3">Add Customer</h2></div><div class="col-4"></div></div>
<div class="row">
<div class="col-12 form-horizontal">
<div class="form-group row">
<div class="col-12 form-group">
<label asp-for="Nama"></label>
<input asp-for="Nama" class="form-control" />
<span asp-validation-for="Nama" class="text-danger"></span>
</div>
<br />
<div class="col-12 form-group">
<label asp-for="Telp"></label>
<input asp-for="Telp" class="form-control" />
<span asp-validation-for="Telp" class="text-danger"></span>
</div>
<br />
<div class="col-12 form-group">
<label asp-for="Alamat"></label>
<input type="text" asp-for="Alamat" class="form-control" />
<span asp-validation-for="Alamat" class="text-danger"></span>
</div>
</div>
<div class="form-group row"><div class="col-6"></div><div class="col-6"></div><div class="col-6"></div></div>
<div class="form-group row">
<div class="col-8 offset-2 row">
<div class="col">
#*change here..........*#
<input type="button" id="btn" class="btn btn-info w-75" value="create" />
</div>
<div class="col">
<a asp-action="Index" class="btn btn-danger w-75">Back</a>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
JS in Create.cshtml:
<script>
$(document).on('click', '#modalCustomer #btn', function () {
var options = {};
options.type = "POST";
options.url = "/Customer/create";
options.dataType = "JSON";
options.cache = false;
options.async = true;
options.data = $("form").serialize();
options.success = function (data) {
//do your stuff...
$('#modalCustomer').modal('hide');
//if you don't want to stay in Index
//add the following code..
// window.location.href = "/home/privacy";
};
options.error = function (res) {
$('#modalBody').html(res.responseText);
};
$.ajax(options);
});
</script>
Update:
If modelstate is invalid, it will get into options.error and display the error message in modal. If modelstate is valid, it will get into options.success, you could redirect by using window.location.href or hide the modal by $('#modalCustomer').modal('hide');, just do your stuff.
Backend code should be like below:
[HttpPost]
[AutoValidateAntiforgeryToken]
public IActionResult Create(Customers obj)
{
if (ModelState.IsValid)
{
_db.Customers.Add(obj);
_db.SaveChanges();
return Json(new { success = true }); //change this...
}
return View(obj);
}

How to pop up the modal div MVC

I want to pop up my div class that contains user at password text box but nothings happen and I test also my function if its running correctly that's why I put alert in my function. This my code bellow. I try so many solution and yet still not show my div. Can any give me a best solution regarding this matter or other way to pop up the web form without leaving my current page.
#model TBSWebApp.Models.User
#{
ViewBag.Title = "UserLogin";
Layout = "~/Layout/_webLayout.cshtml";
}
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
<div>
<fieldset>
<div class="container">
<div class="row">
<div class="col-xs-12">
<button id="btnShowModal" type="button" class="btn btn-sm btn-default pull-left col-lg-11 button button4">
Sign-in
</button>
<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>
<div class="modal-body">
<form>
<div class="form-group">
<input class="form-control" type="text" placeholder="Login Username" id="inputUserName" />
</div>
<div class="form-group">
<input class="form-control" placeholder="Login Password" type="password" id="inputPassword" />
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary button button4">Sign</button>
<button type="button" id="btnHideModal" class="btn btn-primary button button4">
Hide
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</fieldset>
</div>
<footer>
<p style="background-color: Yellow; font-weight: bold; color:blue; text-align: center; font-style: oblique">
©
<script>document.write(new Date().toDateString());</script>
</p>
</footer>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript">
//$(document).ready(function () {
$("#btnShowModal").click(function () {
alert("test");
$("#loginModal").modal('show');
});
$("#btnHideModal").click(function () {
$("#loginModal").modal('hide');
});
// });
</script>
I already solved my problem
<script>
$(document).ready(function () {
$("#submitButton").click(function () {
if (($("#userNameTextBox").val() != "") && ($("#passwordTextBox").val() != ""))
$.ajax(
{
type: "POST", //HTTP POST Method
url: "UserLogin/UserLogin", // Controller/View
dataType: "text/html",
data:
{ //Passing data
UserID: $("#userNameTextBox").val(),
Password: $("#passwordTextBox").val(),
}
});
});
});
//$(document).ajaxStart(function () { $("#loadingImg").show(); });
//$(document).ajaxStop(function () { $("#loadingImg").hide(); });
</script>

Managing state in asp.net mvc C#

On loading the application, table with list of items is displayed.
On clicking the save button, i want to write the list of items to excel.
When i click the save button, in the new request send to the controller,the list is empty.I do not prefer to write the list of table items to database.
Could anyone advice me on how to do handle this?
public IActionResult SaveReport(SalesParentViewModel salesParentViewModel)
{
if(salesParentViewModel.SalesDataModelItems != null)
{
var buffer = new StringBuilder();
buffer.AppendLine("#UserCode,SalesmanName,Date,ItemCode,ItemDescription,BrandCode,BrandName,ClientCode,Client,ClientBranchCode,Description, BranchSubChannel,TransactionAmount,Quantity");
salesParentViewModel.SalesDataModelItems.ToList().ForEach(item => buffer.AppendLine
(String.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13}", item.UserCode, item.SALESMANNAME, item.DATE, item.ItemCode, item.ITEMDESCRIPTION, item.BRANDCODE, item.BRANDNAME, item.ClientCode, item.Client, item.ClientBranchCode, item.Description, item.BRANCHSUBCHANNEL, item.TrxAmount, item.QTY
)));
System.IO.File.WriteAllText("c:\\temp\\file.csv", buffer.ToString());
}
return View();
}
View is as below:
#model MyStoreReports.ViewModels.SalesParentViewModel
#{
ViewBag.Title = "Sales Report";
}
#section scripts{
<script src="~/lib/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.js"></script>
<link rel="stylesheet"
href="http://cdn.datatables.net/1.10.2/css/jquery.dataTables.min.css">
<script type="text/javascript"
src="http://cdn.datatables.net/1.10.2/js/jquery.dataTables.min.js"></script>
<script type="text/javascript"
src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
}
<div class="container-fluid">
<div class="row">
<div class="col-sm-9">
<h1>Sales Report</h1>
</div>
</div>
<div>
<asp:Button id="btnFilter" class="btn btn-sm btn-info" runat="server" Text="Click Me!">
<i class="fa fa-filter"></i>Filter
</asp:Button>
#using (Html.BeginForm("SaveReport", "App", FormMethod.Post))
{
#Html.HiddenFor(model => model.SalesDataModelItems);
<asp:Button id="btnSave" class="btn btn-sm btn-info" onclick="location.href='#Url.Action("SaveReport","App")'" runat="server" Text="Click Me!">
<i class="fa fa-save"></i>Save
</asp:Button>
}
#*<a href="#" class="btn btn-sm btn-info">
<i class="fa fa-save"></i>Save
</a>*#
<a href="#" class="btn btn-sm btn-info">
<i class="fa fa-print"></i>Print
</a>
</div>
<div class="row">
<form method="post">
<asp:Panel id="pnlFilter" runat="server" GroupingText="This is a sample group text" HorizontalAlign="Center">
<div class="col-sm-10" style="background-color:lavenderblush;">
<div class="row">
<div class="col-sm-2">
<label asp-for="SalesViewModelInstance.StartDate">StartDate</label>
<div class="form-group">
<input asp-for="SalesViewModelInstance.StartDate" type="date" class="form-control" />
<span asp-validation-for="SalesViewModelInstance.StartDate" class="text-muted"></span>
</div>
</div>
<div class="col-sm-2">
<label asp-for="SalesViewModelInstance.EndDate">EndDate</label>
<div class="form-group">
<input asp-for="SalesViewModelInstance.EndDate" type="date" class="form-control" />
<span asp-validation-for="SalesViewModelInstance.EndDate" class="text-muted"></span>
</div>
</div>
<div class="row">
<div class="col-sm-1">
<input type="submit" value="Submit" class="btn btn-success" />
</div>
<div class="col-sm-1">
<a asp-controller="App" asp-action="Index" class="btn btn-default">Cancel</a>
</div>
</div>
</div>
</asp:Panel>
</form>
</div>
<div class="form-group">
#if (Model.SalesDataModelItems != null)
{
<div class="container" style="background-color:lavender;" >
<div class="row">
<div class="panel panel-primary">
<div class="panel-heading">
<h2>Report</h2>
</div>
<div class="VScrollTable">
<table id="myTable" class="table table-fixed table-responsive" align="left" cellspacing="0">
<thead>
<tr>
<th>UserCode</th>
<th>SalesmanName</th>
<th>Date</th>
<th>ItemCode</th>
<th>ItemDescription</th>
<th>BrandCode</th>
<th>BrandName</th>
<th>ClientCode</th>
<th>Client</th>
<th>ClientBranchCode</th>
<th>Description</th>
<th>BranchSubChannel</th>
<th>TransactionAmount</th>
<th>Quantity</th>
</tr>
</thead>
#foreach (var item in Model.SalesDataModelItems)
{
<tbody>
<tr>
<td>#item.UserCode</td>
<td>#item.SALESMANNAME</td>
<td>#item.DATE</td>
<td>#item.ItemCode</td>
<td>#item.ITEMDESCRIPTION</td>
<td>#item.BRANDCODE</td>
<td>#item.BRANDNAME</td>
<td>#item.ClientCode</td>
<td>#item.Client</td>
<td>#item.ClientBranchCode</td>
<td>#item.Description</td>
<td>#item.BRANCHSUBCHANNEL</td>
<td>#item.TrxAmount</td>
<td>#item.QTY</td>
</tr>
</tbody>
}
</table>
</div>
</div>
</div>
</div>
}
</div>
</div>
If no change is done in the model, why would you want to pass the entire model from the view to the controller?
Just pass an identifier of some sort like id, and get the data again in the controller and save it in Excel.
If you must pass the model back to the controller it can be done, but the data needs to be hidden inputs or editable input controls (text box, check box)
Your view should look similar to the following :
#model MyStoreReports.ViewModels.SalesParentViewModel
#{
ViewBag.Title = "Sales Report";
}
#section scripts{
<script src="~/lib/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.js"></script>
<link rel="stylesheet"
href="http://cdn.datatables.net/1.10.2/css/jquery.dataTables.min.css">
<script type="text/javascript"
src="http://cdn.datatables.net/1.10.2/js/jquery.dataTables.min.js"></script>
<script type="text/javascript"
src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
}
<div class="container-fluid">
<div class="row">
<div class="col-sm-9">
<h1>Sales Report</h1>
</div>
</div>
<div>
#using (Html.BeginForm("SaveReport", "App", FormMethod.Post))
{
<input id="brnSave" type="submit" class="btn btn-sm btn-info" value="Save" />
<div class="form-group">
#if (Model.SalesDataModelItems != null)
{
<div class="container" style="background-color:lavender;">
<div class="row">
<div class="panel panel-primary">
<div class="panel-heading">
<h2>Report</h2>
</div>
<div class="VScrollTable">
<table id="myTable" class="table table-fixed table-responsive" align="left" cellspacing="0">
<thead>
<tr>
<th>UserCode</th>
<th>SalesmanName</th>
<th>Date</th>
<th>ItemCode</th>
<th>ItemDescription</th>
<th>BrandCode</th>
<th>BrandName</th>
<th>ClientCode</th>
<th>Client</th>
<th>ClientBranchCode</th>
<th>Description</th>
<th>BranchSubChannel</th>
<th>TransactionAmount</th>
<th>Quantity</th>
</tr>
</thead>
#for (int i = 0; i < Model.SalesDataModelItems.Count; i++)
{
<tbody>
<tr>
<td>#Model.SalesDataModelItems[i].UserCode</td>
<td>#Model.SalesDataModelItems[i].SalesManName</td>
<td>#Model.SalesDataModelItems[i].SaleDate</td>
<td>#Model.SalesDataModelItems[i].ItemCode</td>
<td>#Model.SalesDataModelItems[i].ItemDescription</td>
<td>#Model.SalesDataModelItems[i].BrandCode</td>
<td>#Model.SalesDataModelItems[i].BrandName</td>
<td>#Model.SalesDataModelItems[i].ClientCode</td>
<td>#Model.SalesDataModelItems[i].ClientName</td>
<td>#Model.SalesDataModelItems[i].ClientBranchCode</td>
<td>#Model.SalesDataModelItems[i].Description</td>
<td>#Model.SalesDataModelItems[i].BranchSubChannel</td>
<td>#Model.SalesDataModelItems[i].TrxAmount</td>
<td>#Model.SalesDataModelItems[i].Quantity</td>
<td>#Html.HiddenFor(model => model.SalesDataModelItems[i].UserCode) </td>
<td>#Html.HiddenFor(model => model.SalesDataModelItems[i].SalesManName) </td>
<td>#Html.HiddenFor(model => model.SalesDataModelItems[i].SaleDate) </td>
<td>#Html.HiddenFor(model => model.SalesDataModelItems[i].ItemCode) </td>
<td>#Html.HiddenFor(model => model.SalesDataModelItems[i].ItemDescription) </td>
<td>#Html.HiddenFor(model => model.SalesDataModelItems[i].BrandCode) </td>
<td>#Html.HiddenFor(model => model.SalesDataModelItems[i].BrandName) </td>
<td>#Html.HiddenFor(model => model.SalesDataModelItems[i].ClientCode) </td>
<td>#Html.HiddenFor(model => model.SalesDataModelItems[i].ClientName) </td>
<td>#Html.HiddenFor(model => model.SalesDataModelItems[i].ClientBranchCode) </td>
<td>#Html.HiddenFor(model => model.SalesDataModelItems[i].Description) </td>
<td>#Html.HiddenFor(model => model.SalesDataModelItems[i].BranchSubChannel) </td>
<td>#Html.HiddenFor(model => model.SalesDataModelItems[i].TrxAmount) </td>
<td>#Html.HiddenFor(model => model.SalesDataModelItems[i].Quantity) </td>
</tr>
</tbody>
}
</table>
</div>
</div>
</div>
</div>
}
</div>
}
</div>
</div>
And like Tetsuya Yamamoto pointed out, avoid mixing asp web forms controls in asp.net MVC application
EDIT (After Maria comments) :
You can add an ajax call to save the data in excel on button press :
Controller Savereport method :
public ActionResult SaveReport()
{
try
{
// Get data from DB and save it in excel
return Json("Success save report");
}
catch (Exception ex)
{
return Json("Save report failure!" + ex.Message);
}
}
View :
#model MVCWebApplication.Controllers.SalesParentViewModel
#{
ViewBag.Title = "Sales Report";
}
#section scripts{
<link rel="stylesheet"
href="http://cdn.datatables.net/1.10.2/css/jquery.dataTables.min.css">
<script type="text/javascript"
src="http://cdn.datatables.net/1.10.2/js/jquery.dataTables.min.js"></script>
<script type="text/javascript"
src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
}
<div class="container-fluid">
<div class="row">
<div class="col-sm-9">
<h1>Sales Report</h1>
</div>
</div>
<div>
<input id="btnSave" type="button" class="btn btn-sm btn-info" data-url="#Url.Action("SaveReport","App")" value="Save" />
<div class="form-group">
#if (Model.SalesDataModelItems != null)
{
<div class="container" style="background-color:lavender;">
<div class="row">
<div class="panel panel-primary">
<div class="panel-heading">
<h2>Report</h2>
</div>
<div class="VScrollTable">
<table id="myTable" class="table table-fixed table-responsive" align="left" cellspacing="0">
<thead>
<tr>
<th>UserCode</th>
<th>SalesmanName</th>
<th>Date</th>
<th>ItemCode</th>
<th>ItemDescription</th>
<th>BrandCode</th>
<th>BrandName</th>
<th>ClientCode</th>
<th>Client</th>
<th>ClientBranchCode</th>
<th>Description</th>
<th>BranchSubChannel</th>
<th>TransactionAmount</th>
<th>Quantity</th>
</tr>
</thead>
#foreach (var item in Model.SalesDataModelItems)
{
<tbody>
<tr>
<td>#item.UserCode</td>
<td>#item.SalesManName</td>
<td>#item.SaleDate</td>
<td>#item.ItemCode</td>
<td>#item.ItemDescription</td>
<td>#item.BrandCode</td>
<td>#item.BrandName</td>
<td>#item.ClientCode</td>
<td>#item.ClientName</td>
<td>#item.ClientBranchCode</td>
<td>#item.Description</td>
<td>#item.BranchSubChannel</td>
<td>#item.TrxAmount</td>
<td>#item.Quantity</td>
</tr>
</tbody>
}
</table>
</div>
</div>
</div>
</div>
}
</div>
</div>
</div>
<script>
$(function () {
$('#btnSave').on('click', function () {
$.ajax({
url: $(this).data('url'),
type: 'post',
datatype: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
console.log(data);
},
error: function (xhr) {
console.log(JSON.parse(xhr.responseText));
}
});
});
});
</script>

Error: [ng:areq] Argument 'approvalCtrl' is not a function, got undefined

i create a project to show data from database to gridview with a code like this
this is for approval.html
<style type="text/css">
.auto-style4 {
width: 260px;
height: 50px;
}
.auto-style5 {
width: 292px;
height: 50px;
}
.auto-style6 {
width: 850px;
height: 50px;
}
.auto-style13 {
width: 260px;
height: 54px;
}
.auto-style14 {
width: 292px;
height: 54px;
}
.auto-style15 {
width: 850px;
height: 54px;
}
</style>
<style>
.panel-default > .panel-heading {
color: #f5ffff;
background-color: #6d1014;
}
.auto-style20 {
width: 260px;
height: 64px;
}
.auto-style21 {
width: 292px;
height: 64px;
}
.auto-style22 {
width: 850px;
height: 64px;
}
.auto-style23 {
width: 260px;
height: 10px;
}
.auto-style25 {
width: 129px;
}
.auto-style26 {
width: 292px;
height: 10px;
}
</style>
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-10">
<div class="panel panel-default" style="width: 900px;">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">
Approval
</a>
</h4>
</div>
<div id="collapseTwo" class="collapse in">
<div class="panel-body">
<div class="row">
<div class="col-md-1">
<table>
<tr>
<td></td>
</tr>
</table>
</div>
<div class="col-lg-10">
<form class="form-horizontal">
<div class="form-group">
<br />
<!--ROW 1 = Period -->
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-2">
<label for="labelPeriod" class="control-label">Period</label>
</div>
<div class="col-md-4">
<input id="txtOldDate" max="txtNewDate" type="date" class="datepicker" />
</div>
<div class="col-md-1">
<label for="labelTo" class="control-label">To</label>
</div>
<div class="col-md-4">
<input id="txtNewDate" min="txtOldDate" type="date" class="datepicker" />
</div>
<div class="col-md-4"></div>
</div>
<br />
<!--ROW 2 = Department-->
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-2">
<label for="labelDepartment" class="control-label">Department</label>
</div>
<div class="col-md-5">
<div class="side-by-side clearfix">
<div class="dropdown">
<select id="ddlDepartment" class="form-control">
<option>EDP Department</option>
<option>Departemen 2</option>
<option>Departemen 3</option>
</select>
</div>
</div>
</div>
<div class="col-md-5"></div>
</div>
<!--ROW 3 = Employee-->
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-2">
<label for="labelEmployee" class="control-label">Employee</label>
</div>
<div class="col-md-5">
<div class="side-by-side clearfix">
<div class="dropdown">
<select id="ddlManagerApproval" class="form-control">
<option>Manager 1</option>
<option>Manager 2</option>
<option>Manager 3</option>
</select>
</div>
</div>
</div>
<div class="col-md-5"></div>
</div>
<br />
<!--ROW 4 = Button Show Data-->
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-2">
<input id="btnSubmit" type="button" class="btn btn-primary" value="Show" />
</div>
<div class="col-md-9"></div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<!--ROW 5 = Gridview-->
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-2"></div>
<div class="col-md-5"></div>
</div>
<br />
<div ng-controller="approvalCtrl" class="row">
<div class="col-md-1"></div>
<div class="col-md-10">
<table class="table table-bordered table-hover">
<tr style="background-color:#6d1014; color:#FFFFFF">
<th>Ticket Number</th>
<th>Requester Account</th>
<th>Category</th>
<th>Sub Category</th>
<th>Subject</th>
<th>Body</th>
<th>FIle Name</th>
<th>Assigned To</th>
</tr>
<tbody ng-repeat="e in requestList">
<tr>
<td>{{e.TICKET_NUMBER}}</td>
<td>{{e.REQUESTER}}</td>
<td>{{e.CATEGORY}}</td>
<td>{{e.SUBCATEGORY}}</td>
<td>{{e.SUBJECT}}</td>
<td>{{e.BODY}}</td>
<td>{{e.CATEGORY}}</td>
<td>{{e.FILE_NAME}}</td>
<td>{{e.ASSIGNED_TO}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
this is approvalCtrl.js
(function (app) {
'use strict';
app.controller('approvalCtrl', function ($scope, GetDataService) {
function getAllDataRequest() {
GetDataService.getRequestData().then(function (emp) {
$scope.requestList = emp.data;
}, function (error) {
alert('failed to fetch data');
});
}
})(angular.module('myapplication'));
});
This is the approvalController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MyApplication.Service.Controllers
{
public class ApprovalController : Controller
{
// GET: Approval
public ActionResult Index()
{
return View();
}
public JsonResult GetAll()
{
List<TRN_SERVICE_REQUEST> reqdata = new List<TRN_SERVICE_REQUEST>();
using (RREntities ed = new RREntities())
{
reqdata = ed.TRN_SERVICE_REQUEST.ToList();
return new JsonResult { Data = reqdata, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
}
}
This is the app.js
(function () {
'use strict';
var app = angular.module('myapplication', ['common.core', 'common.ui'])
.config(config)
.run(run);
config.$inject = ['$routeProvider'];
function config($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "scripts/spa/home/index.html",
controller: "indexCtrl"
})
.when("/entry", {
templateUrl: "scripts/spa/entry/entry.html",
controller: "entryCtrl"
})
.when("/approval", {
templateUrl: "scripts/spa/approval/Approval.html",
controller: "approvalCtrl"
});
}
run.$inject = ['$rootScope', '$location', '$cookieStore', '$http'];
function run($rootScope, $location, $cookieStore, $http) {
// handle page refreshes
$rootScope.repository = $cookieStore.get('repository') || {};
if ($rootScope.repository.loggedUser) {
$http.defaults.headers.common['Authorization'] = $rootScope.repository.loggedUser.authdata;
}
$(document).ready(function () {
$(".fancybox").fancybox({
openEffect: 'none',
closeEffect: 'none'
});
$('.fancybox-media').fancybox({
openEffect: 'none',
closeEffect: 'none',
helpers: {
media: {}
}
});
$('[data-toggle=offcanvas]').click(function () {
$('.row-offcanvas').toggleClass('active');
});
});
}
})();
The page result is shown in this image
Result Page
Why the result is getting an error is not a function?
Thanks in advance
It seems to me that you've written the self-invoking function wrong. The arguments weren't placed rightly. Should've been one line below.
(function (app) {
'use strict';
app.controller('approvalCtrl', function ($scope, GetDataService) {
function getAllDataRequest() {
GetDataService.getRequestData().then(function (emp) {
$scope.requestList = emp.data;
}, function (error) {
alert('failed to fetch data');
});
}
});
})(angular.module('myapplication'));
You need to define the app in your HTML
<div ng-app = "myapplication"></div>

refresh a partial view in mvc

i'm having a detail view in which there will be a conversation, and even comment box in conversation. I had a comment box in partial view. but had an issue when decided to refresh just the conversation on creating comment.
I know i can bind below code in partial view. but i have difficulty in calling action method for it.
So it will have details view code and then below code
<div class="row">
<div class="panel-group" id="accordion">
#foreach (var convo in Model.TicketConversation.OrderByDescending(x => x.LastUpdatedTimestamp))
{
<div class="col-md-10 col-md-offset-1" style="padding-bottom: 5px;">
<div class="panel panel-default">
<div class="panel-heading removePaddingBottom" data-toggle="collapse" data-target="#accord-convo-#convo.id" style="background-color: inherit;" id="accordHeading-#convo.id" onclick="javascript:showHideLastConvoMsg(#convo.id)">
<a style="text-decoration: none !important; color: inherit; width: 100px;">
<span style="font-size: 16px; font-weight: bold; vertical-align: middle !important;"><i class="fa fa-chevron-right" id="accord-heading-icon-#convo.id"></i> #convo.Subject</span>
</a>
#{ var lastmessage = convo.ConversationComments.First(); }
<div class="row">
<div id="accord-lastmsg-#convo.id" style="margin-top: 15px;">
<div class="#lastmessage.DisplayCssClass">
<div class="row">
<div class="col-md-offset-1 col-md-10 removePadding" style="margin-bottom: 5px; margin-top: 10px;">
<strong>#lastmessage.TypeOfContact</strong>
</div>
<div class="col-md-offset-1 col-md-10 removePadding" style="margin-bottom: 10px;">
#lastmessage.Message
</div>
</div>
<div class="row">
<div class="col-md-offset-6 col-md-5 text-right text-muted" style="margin-bottom: 10px;">
<small>
<em>Posted by #lastmessage.CommenterName ## #lastmessage.MessageTimestamp</em>
</small>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="accord-convo-#convo.id" class="panel-collapse collapse">
<div class="panel-body" style="padding: 0;">
#if (convo.IsReadOnly == false #*&& Model.IsClosed == false*#)
{
<div class="row">
#*<div class="col-md-12" style="padding-bottom: 3px; padding-top: 3px;">
<i class="fa fa-reply"></i> Reply
</div>*#
---- here i'm calling partial view for comment box---
}
#foreach (var item in convo.ConversationComments)
{
<div>
<div class="message-border #item.DisplayCssClass">
<div class="row">
<div class="col-md-offset-1 col-md-10 removePadding" style="margin-bottom: 5px;">
<strong>#item.TypeOfContact</strong>
</div>
<div class="col-md-offset-1 col-md-10 removePadding" style="margin-bottom: 10px;">
#item.Message
</div>
</div>
<div class="row">
<div class="col-md-5 text-right text-muted">
<small>
<em>Posted by #item.CommenterName ## #item.MessageTimestamp</em>
</small>
</div>
</div>
</div>
</div>
}
</div>
</div>
</div>
</div>
}
</div>
</div>
which method can be called to get conversation list?? do i need to write a new action method.
You can create a Action method that return a partial view for the conversation you have. For ex:
public class SomeCtrlController : Controller
{
public PartialViewResult Conversation(int id)
{
List<Conversation> conversations = new List<Conversation>();
//Use id to create your Model and pass it to Partial View
conversations = PopulateConversations(id);
// The below code search for Conversation.cshtml inside Views\SomeCtrl folder
return PartialView(conversations);
}
}
Then from your cshtml (razor view) you can call it like for first time loading:
#{ Html.RenderAction("Conversation", "SomeCtrl", new { id = 1 /*this will be id for which conversion have to load */ });}
Then to refresh just conversations you can use jQuery ajax or get method. This will refresh only section of the which you have specified. See example below
<script>
var conversationData = {
"id": 1 /*this will be id for which conversion have to load */
};
$.get("/SomeCtrl/Conversation", conversationData,
function (returnedHtml) {
$("#placeHolderDivToHaveConversation").html(returnedHtml);
});
</script>
when I need to do this, I work with jquery ajax. For example:
I need to load this div below dynamically:
Button View
<button id="buscarVideos" class="btn">Buscar</button>
I call my ajax in one event and load de result there:
Success ajax
$("#partial_video").html(data);
Partial
<div class="col-lg-12">
<div id="partial_video">
#*#Html.Partial("_Player")*#
</div>
</div>
Return on Controller:
return PartialView("_Player", video);

Categories

Resources