model not passing to controller from view - javascript

I am new to mvc and javascript.At first I am using javascript to appned the parital view in divsion
$('.btngo').click(function (e) {
var fid = $('#FiscalYear_FYId').val();
alert($('#FiscalYear_FYId').val());
$.ajax({
type: 'Get',
url: '#Url.Action("RateList", "Rate")',
data: { fyid: fid },
success: function (sc) {
$('#Ratelist').html(sc);
}
});
});
The partial view is of model FHIControl.Model.StationeryRate.RateDTO which consists a submit button my view looks like
#using (Html.BeginForm("Ratelist", "Rate", FormMethod.Post))
{
#Html.ValidationSummary(true)
<table>
<thead>
<tr>
<th>Item Id</th>
<th>Item Name</th>
<th>Rate</th>
</tr>
</thead>
#Html.HiddenFor(x=>Model.FiscalYear.FYId)
#foreach (var item in Model.RateList)
{
<tr>
#Html.HiddenFor(x => item.ItemId)
<td>#{count++;}#count</td>
<td>#Html.DisplayFor(x => item.ItemName)</td>
<td>#Html.TextBoxFor(x => item.Rate)</td>
</tr>
}
</table>
<p>
<input type="submit" value="Ok" id="btnsubmit" />
</p>
}
The button submit is submiting the form but there is no model items.Why is it so?Is there any way to make this work?

There is no model items because you are only passing the value of FiscalYear_FYId:
var fid = $('#FiscalYear_FYId').val();
$.ajax({
data: { fyid: fid },
});
which should be:
$.ajax({
data: $form.serialize(),
});
where $form is a reference to your form. That you can either give a name for faster and better reference, or you can reference it like this:
var $form = $("#btnsubmit").parents('form');

Related

How can I give Ajax data (list) to mustache?

I want to put the user object I received as Ajax into {{#user}} in mustache and render it on the screen.
<table class="table table-horizontal table-bordered">
<thead class="thead-strong">
<tr>
<th>user number</th>
</tr>
</thead>
<tbody id="tbody">
{{#users}}
<tr>
<td>{{id}}</td>
</tr>
{{/users}}
</tbody>
</table>
this is conroller
#PostMapping("/api/v1/eduPosts/registerAdminToUser")
public List<User> registerAdminToUser(#RequestBody UserRegisterRequestDto userRegisterRequestDto){
List<User> users=userService.registerAdminToUser(userRegisterRequestDto);
System.out.println(users);
return users;
}
this is index.js
update : function () {
var data = {
adminId: $('#adminId').val(),
userId: $('#userId').val()
};
//var id = $('#id').val();
$.ajax({
type: 'POST',
url: '/api/v1/eduPosts/registerAdminToUser',
dataType: 'json',
contentType:'application/json; charset=utf-8',
data: JSON.stringify(data)
}).done(function(data) {
$.each(data, function(idx, val) {
alert(idx + " " + val.id);
console.log(idx + " " + val.id)
});
alert(JSON.stringify(data))
}).fail(function (error) {
alert(JSON.stringify(error));
});
}
Should I change the js file? Or do I have to change the mustache template?
If I print out the user object in the index.js file, the data is being rendered properly.
Thanks!

Get ID on click of a button AJAX way

I am building a small application using ASP.NET MVC Core 3.1.
I am displaying few buttons on the View. Each row has a button. When a button is clicked corresponding to a row, I want to get the ID value of this row but without page refresh. It should be done using AJAX.
The View code is something like this:
#using Updater.Models
#model IEnumerable<TemplateData>
#{
Layout = null;
}
#{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
#if (Model.Count() > 0)
{
<hr />
<table cellpadding="0" cellspacing="0" border="1" style="height:600px">
<tr>
<th>ID</th>
<th>Location</th>
<th>Observation Type</th>
<th>EmpName</th>
<th>Status</th>
</tr>
#foreach (TemplateData sheet in Model)
{
<tr>
<td>#sheet.ID</td>
<td>#sheet.Location</td>
<td>#sheet.ObservationType</td>
<td>#sheet.EmpName</td>
<td>
#Html.DropDownList("CI Status", new List<SelectListItem>
{
new SelectListItem{ Text="", Value = "0" },
new SelectListItem{ Text="Completed", Value = "1" },
new SelectListItem{ Text="In-Progress", Value = "2" },
new SelectListItem{ Text="Review", Value = "3" },
})
</td>
</tr>
<tr>
<td>
#using (Html.BeginForm("Index", "sheet", FormMethod.Post))
{
<input type="submit" value="Update Status" class="ids" data-id="#sheet.ID" />
}
</td>
</tr>
}
</table>
}
</div>
<script type="text/javascript">
$('.ids').click(function() {
var rowID = $(this).data('id');
alert(rowID);
});
</script>
** Edited **
In continuation of what Costa suggested below to call controller from Javascript, I attempted below code, but instead of showing message, it is directing to URL: http://localhost/sheet
<tr>
<td>
#using (Html.BeginForm("Index", "sheet", FormMethod.Post))
{
<input type="submit" id="btnSubmit" value="Update Status" class="ids" data-id="#sheet.ID" onClick="UpdateStatus(#sheet.ID)"/>
}
</td>
</tr>
}
</table>
}
</div>
<script type="text/javascript">
$.ajax({
type: "POST",
url: '#Url.Action("Home", "UpdateStatus")',
contentType: "application/json; charset=utf-8",
data: id,
dataType: "json",
success: function() { alert('Success'); },
error: function() { alert('Error'); }
});
</script>
Controller Code
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
[HttpPost]
[Route("UpdateStatus")]
public void UpdateStatus()
{
//Do Something
}
}
If you want to pass the ID to javascript, you can use this:
<input type="submit" value="Update Status" class="ids" data-id="#sheet.ID" onClick="UpdateStatus(#sheet.ID)" />
<script>
function UpdateStatus(string id) {
$.ajax({
type: "POST",
url: "/UpdateStatus",
contentType: "application/json; charset=utf-8",
data: {"id": id},
dataType: "json",
success: function() { alert('Success'); },
error: function() { alert('Error'); }
});
}
</script>
Finally, edit your controller like this:
[HttpPost]
[Route("UpdateStatus/{id}")]
public void UpdateStatus(string id)
{
//Do Something
}

How to pass model from partialView to javascript in asp.net mvc

I wanna pass down model from partialView to javascript and process it in controller,
now the problem is i couldn't pass the model where when i run the code it show null. can anyone help me on this?
*HTML code
#model List<TPMS.Models.Draft_SingleValue>
<div class="row">
<div class="col-lg-12">
<table class="table table-bordered">
<thead>
<tr class="bg-gray">
<th>Keyword</th>
<th>Default Value <span class="pull-right"><i class="fa fa-edit"></i></span></th>
<th><span class="pull-right"><i></i></span></th>
</tr>
</thead>
<tbody>
#foreach (var sdata in Model.OrderBy(i => i.Keyword))
{
<tr id="#sdata.DraftSingleValue_ID">
<td id="sv:#sdata.DraftSingleValue_ID:Keyword" contenteditable="false">#sdata.Keyword</td>
<td id="sv:#sdata.DraftSingleValue_ID:Default_Value" contenteditable="false"> #sdata.Default_Value</td>
<td id="sv:#sdata.DraftSingleValue_ID" contenteditable="false" class="">
<span class="btn-group center-block" id="PlusButton">
<a class="btn btn-success btn-xs" href="javascript:AddKeyword('#sdata');" data-id="#sdata"><i class="fa fa-plus"></i> </a>
</span>
</td>
</tr>
}
</tbody>
<tfoot>
<tr class="bg-gray">
<th>Keyword</th>
<th>Default_Value <span class="pull-right"><i class="fa fa-edit"></i></span></th>
<th><span class="pull-right"><i></i></span></th>
</tr>
</tfoot>
</table>
</div>
</div>
*Javascript
function AddKeyword(SvModel) {
debugger
//var model = $('#Testing').attr('data-id');
$.ajax({
url: "#Url.Action("AddSingleValue", "Draft")",
cache: false,
type: "GET",
datatype: 'html',
data: {"Model": SvModel },
success: function (data) {
$('#List_Keyword').modal('hide');
$("#List_SVKeywords").html(data);
$('#List_Keyword').modal('show');
},
error: function () {
alert('Failed to retrieve values.');
document.getElementById("del_err_span_dialog").innerHTML = "Fatal Error, Please try again.";
}
});
}
*Controller
public ActionResult AddSingleValue(Draft_SingleValue Model)
{
Draft_SingleValue svmodel = new Draft_SingleValue();
svmodel.Draft_File_ID = Model.Draft_File_ID;
svmodel.Data_Type = Model.Data_Type;
svmodel.Group_Name = Model.Group_Name;
svmodel.Is_Active = Model.Is_Active;
svmodel.Keyword = Model.Keyword;
svmodel.Max_Length = Model.Max_Length;
svmodel.Min_Length = Model.Min_Length;
svmodel.Modified_By = User.Identity.Name;
svmodel.Modified_On = DateTime.Now;
svmodel.Remarks = Model.Remarks;
svmodel.Default_Value = Model.Default_Value;
_temporaryrepo.Insert_TemporarySingleValue(svmodel);
return ListSv(svmodel.Draft_File_ID);
//return new EmptyResult();
}
As you guys can c from above code, im trying to pass model to AddKeyword function but i cant. it will be great if anyone can show me a way to do this.
Try this:
View:
#using (Html.BeginForm("YourActionMethod", "YourController", FormMethod.Post,
new { id = "frmCreate", enctype = "multipart/form-data" }))
{
//code omitted for brevity
}
<script>
$(function () {
$('form').submit(function (event) {
event.preventDefault();
var formdata = new FormData($('#frmCreate').get(0));
$.ajax({
type: "POST",
url: '#Url.Action("YourActionMethod", "YourController")',
data: formdata, //! your model data
dataType: "json",
success: function (response) {
if (response.success) {
//success
}
else {
//error
}
}
});
});
});
</script>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult YourActionMethod([Bind(Exclude = null)] Model viewModel)
{
//...
return Json(new { success = true, message = "Success!.." },
JsonRequestBehavior.AllowGet);
}

Foreach Data not reflected to UI with Knouckout Js Object Obserable

Below is the view modal where I am getting the ajax response and load to the obserable value.
var userManagementVM = {
responseSetUpData: ko.observable({
userList: ko.observable(),
userListViewModel: ko.observableArray(),
MeetingId: ko.observable(),
MeetingTypeId: ko.observable(),
MeetingType: ko.observable()
}),
SetListOfUserInRoles: function () {
var self = this;
var ajaxUrl = ApplicationRootUrl("UserRoleManagement", "UserManagement");
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: ajaxUrl,
dataType: "json",
success: function (data) {
self.responseSetUpData(data);
console.log(self.responseSetUpData())
},
error: function (err) {
}
});
}
}
$(document).ready(function () {
ko.applyBindings(userManagementVM, document.getElementById("rightdash-container"));
userManagementVM.SetListOfUserInRoles();
});
The response from the ajax is successfully loaded to the obserable value. Below is the output of the console
HTML code
<table class="table table-striped">
<thead>
<tr>
<th scope="col">Users</th>
<th scope="col">Role</th>
</tr>
</thead>
<tbody data-bind="foreach: responseSetUpData.userListViewModel">
<tr>
<td><input class="form-check-input" type="checkbox" data-bind="checked: SelectedUser"><span data-bind="text: $data.FirstName"></span></td>
<td><select data-bind="options: $data.Roles,optionsText: 'Name',value: $data.SelectedRoleId,optionsCaption: '-- Select Role --'"></select></td>
</tr>
</tbody>
</table>
The value is not bind to the UI.
You need to get the value of the observable - responseSetUpData() in the binding:
<tbody data-bind="foreach: responseSetUpData().userListViewModel">
Otherwise you are trying to get userListViewModel from the observable function object :-)

Dynamically adding table rows with functions

I have a table that I need to dynamically add/remove rows from. Each row has a hyperlink in the final column to remove the record. Since you can dynamically add rows after the page loads, occasionally this record won't be found in the database.
When the user clicks on the "Delete" link, an ajax function is called to remove the record from the database. As long as the function server-side function does not crash, the operation will send back as a success.
Once the ajax function's success function is called, I would like to remove the tr from the table.
I can do this with each row that exists in the table once the page loads. The ajax function sends the proper info back to the server, and the tr is removed from the table. However for each tr I add after the delete ajax function will not fire, and the tr is left on the page.
View
<fieldset>
<legend>Agent Ids</legend>
<table id="agentTable">
<thead>
<tr>
<th>State Code</th>
<th>Company Code</th>
<th>Agent ID</th>
<th>Non-Res Biz NY</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.BankListAgentIds)
{
#Html.Partial("AgentIdPartial", item)
}
</tbody>
Add Another
</table>
</fieldset>
Parial View
#model CollectionItemTest.Models.BankListAgentId
#{
Layout = null;
}
#using (Html.BeginCollectionItem("BankListAgentIds"))
{
#Html.HiddenFor(model => model.TableId)
#Html.HiddenFor(model => model.BankID)
<tr>
<td>
#Html.EditorFor(model => model.StateCode)
</td>
<td>
#Html.EditorFor(model => model.CompanyCode)
</td>
<td>
#Html.EditorFor(model => model.NonResBizNY)
</td>
<td>
#Html.EditorFor(model => model.AgentId)
</td>
<td>
#Html.ActionLink("Delete", "", "", new { href = "javascript:void(0)", id = Model.TableId })
</td>
</tr>
}
jQuery
<script type="text/javascript">
$(function() {
$('#agentTable').on('click', 'tr a', function(e) {
$.ajax({
url: '#Url.Action("DeleteRow", "BankList")',
data: { id: $(this).attr('id') },
dataType: 'html',
cache: false,
context: this,
success: function () {
$(this).parents('tr').remove();
}
});
})
});
$(document).ready(function () {
$('.addCode').click(function() {
$.ajax({
url: '#Url.Action("BlankRow", "BankList")',
dataType: 'html',
cache: false,
success: function(html) {
$("#agentTable > tbody").append(html);
}
});
});
});
</script>
Controller Functions
public JsonResult DeleteRow(int id)
{
if (id == 0) return null;
var agent = (from a in db.BankListAgentIds
where a.TableId == id
select a).FirstOrDefault();
if (agent == null) return Json("Agent Id not found", JsonRequestBehavior.AllowGet);
db.BankListAgentIds.Remove(agent);
return null;
}
public ViewResult BlankRow()
{
return View("AgentIdPartial", new BankListAgentId());
}
Followed this post and used the .live command.
$('#agentTable').live('click', 'tr a', function (e) {
$.ajax({
url: '#Url.Action("DeleteRow", "BankList")',
data: { id: $(this).attr('id') },
dataType: 'html',
cache: false,
context: this,
success: function () {
$(this).parents('tr').remove();
}
});
});

Categories