I am trying to get user input in button click.
When user insert number and press Check, it needs to return xml data type.
So in my controller I create function which will return a data for passing ID
[ResponseType(typeof(AKONTA))]
public IHttpActionResult GetAKONTA(string id)
{
AKONTA aKONTA = db.AKONTAS.Find(id);
if (aKONTA == null)
{
return BadRequest("Ne postoji A_KONTO pod tim rednim brojem");
}
return Ok(aKONTA);
}
And In my View I have following
<br /><br />
<form>
<div class="form-group">
<label>A_KONTO</label>
<input type="text" class="form-control" aria-describedby="AKONTO BROJ" placeholder="Unesite broj AKONOTO">
</div>
<div class="form-group">
<a asp-action="Index" class="btn btn-primary" id="aKonto" action="#Url.Action("GetAKONTA", "Akontas")">Provjeri</a>
</div>
</form>
And I want to create in btn click when user pass ID it needs to return XML data format.
SO far I create a JS function, but I don't know JavaScript and don't know the logic how to pass Controller Action Result to JS.
<script>
$(document).ready(function () {
$('#aKonto').click(function () {
document.getElementById("aKonto").onclick = function () {GetAKONTA()};;
});
});
</script>
If someone can help me I would be very thankful.
Cheers !
UPDATE
function aKontoSubmit() {
$.ajax({
type: "GET",
url: 'api/Akontas',
//data: { id: id },
dataType: "xml",
success: function (result) {
// action to do after form submit
},
error: function () {
alert("Ne postoji AKONTO pod tim rednim brojem");
}
});
}
**routeConfig**
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace AkontasWebApi
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
Add Reference of Jquery, to try the ajax call method.
function aKontoSubmit() {
$.ajax({
type: "POST",
url: '/Akontas/GetAKONTA',
data: $('form').serialize(),
dataType: "json",
success: function (result) {
// action to do after form submit
},
error: function () {
alert("Error while inserting data");
}
});
}
Change you Link Code as Below
<a asp-action="Index" class="btn btn-primary" id="aKonto" onClick='return aKontoSubmit() '>Provjeri</a>
Or Else You Can try if you are using ASP.Net MVC Core Development
<form asp-action="GetAKONTA" asp-controller="Akontas" method="post">
<div class="form-group">
<label>A_KONTO</label>
<input type="text" class="form-control" aria-describedby="AKONTO BROJ" placeholder="Unesite broj AKONOTO">
</div>
<div class="form-group">
<input class="btn btn-primary" id="aKonto" type = "submit" value = "Provjeri" />
</div>
</form>
After a couple hours of debugging and searching I found that I forget to put
window.location.href = "http://localhost:57285/api/Akontas/" + $('#AkontasId').val();
This is location where should redirect if item exsist in database
And URL call need to be modified as well
URL: "/api/Akontas/GetAKONTA",
function aKontoSubmit() {
$.ajax({
type: "GET",
URL: "/api/Akontas/GetAKONTA",
data: { id: $('#AkontasId').val() },
contentType: "data/xml; charset=utf-8",
success: function (result) {
window.location.href = "http://localhost:57285/api/Akontas/" + $('#AkontasId').val();
},
error: function () {
alert("Ne postoji AKONTO pod tim rednim brojem");
}
});
}
Related
net core and I'm building a to do list app to learn but iv hit a road block trying to add an item to a to do list with out refreshing the page.
With my current setup the controller method to add a todo item to DB and a script to get refresh the html on page are called on form submit but the html is updated before item is added to DB.
Any suggestions on how to fix this or what is the best way to go about doing this would be greatly appreciated.
My Div for Table:
<div id="tableDiv"></div>
My Input form:
<div id="addTodoForm">
<form asp-action="AddToDoForm" method="post" data-ajax="true" >
<input asp-for="Item" class="form-control " placeholder="Add To Do Item.." />
</form>
</div>
My Script To update html (has a time out function as a temporary fix to this issue)
<script>
$("#addTodoForm").submit(function()
{
setTimeout(function(){
$.ajax({
type: "POST",
url: '/ToDos/BuildToDoTable',
success: function (result) {
$('#tableDiv').html(result);
}
})
}, 500);
})
</script>
My method to add Item to DB:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddToDoForm([Bind("Id,Item")] ToDo toDo)
{
if (ModelState.IsValid)
{
string currentUserId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
IdentityUser currentUser = _context.Users.FirstOrDefault(x => x.Id == currentUserId);
toDo.User = currentUser;
toDo.Status = false;
_context.Add(toDo);
await _context.SaveChangesAsync();
}
return BuildToDoTable();
}
Not sure what is your whole code, here is a simple working demo about how to post data to backend and display the data from backend without refreshing:
View:
#model ToDo
<div >
<form method="post" id="addTodoForm">
<input asp-for="Id" class="form-control "/>
<input asp-for="Item" class="form-control " placeholder="Add To Do Item.." />
//focus here...it is type of button and add an onclick event here.....
<input type="button" value="Create" class="btn btn-primary" onclick="PostData()" />
</form>
</div>
<div id="tableDiv"></div>
#section Scripts {
<script>
function PostData() {
$.ajax({
type: "POST",
data: $("#addTodoForm").serialize(), //using this way to get the form data
url: '/Home/AddToDoForm',
success: function (result) {
$('#tableDiv').html(result);
}
})
}
</script>
}
Controller:
public class HomeController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddToDoForm([Bind("Id,Item")] ToDo toDo)
{
return PartialView("Partial", toDo);
}
}
Partial.cshtml(jsut a easy view for testing):
#model ToDo
#Model.Item //display the data
You can use e.preventDefault() which prevents the default behavior of submitting your form (refresh the page).
<script>
$("#addTodoForm").submit(function(e)
{
e.preventDefault();
$.ajax({
type: "POST",
url: '/ToDos/BuildToDoTable',
success: function (result) {
$('#tableDiv').html(result);
}
});
})
</script>
use this code:
<script>
$("#addTodoForm").submit(function(e)
{
e.preventDefault();
$.ajax({
type: "POST",
url: '/ToDos/BuildToDoTable',
success: function (result) {
$('#tableDiv').html(result);
}
});
location.reload();
})
</script>
In a non-Razor environment with simple HTML, CSS and AJAX, easily done, but from within Razor Pages?
Let's say I have a simple button based on a backend state of (success,danger) like:
<div id="UpdateButonStatusEvery2s">
<button type="button" class="btn btn-success">Success</button>
</div>
and I want to reflect a change in the backend state to "danger" in the button
<div id="UpdateButonStatusEvery2s">
<button type="button" class="btn btn-danger">Danger</button>
</div>
How do I achieve that?
I figured I have to run the usual setinterval() in AJAX, but how do I get the Razor backend to respond with the HTML fragment id="UpdateButonStatusEvery2s"?
You can try this code in your razor-page.
First add this code in your startup:
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
Then in your razor:
#page
#model ButtonDemoModel
#Html.AntiForgeryToken()
<div id="UpdateButonStatusEvery2s">
<button type="button" class="btn btn-success" value="success">Success</button>
</div>
#section Scripts
{
<script>
$("button").click(function (e) {
var data = $(this).val();
$.ajax({
type: "POST",
url: "?handler=test",
data: { data: data },
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
dataType: "json",
success: function (response) {
if (response.result == "danger")
{
var newRow = '<button type="button" class="btn btn-danger" value="danger">' + response.result +'</button>';
$('#UpdateButonStatusEvery2s').html(newRow);
}
}
});
});
</script>
}
The backend code:
public class ButtonDemoModel : PageModel
{
public void OnGet()
{
}
public IActionResult OnPostTest(string data)
{
//here you can change the data,do your logic.
data = "danger";
return new JsonResult(new { result = data });
}
}
Test result:
Similar effect can be accomplished from c# using Task.ContinueWith()
For example:
Task.Delay(2000).ContinueWith(x => Console.WriteLine("I'm back"));
I am using some javascript to post my form but I dont want to have to submit each form field is there a way I can serlize this to an object in .net so that it will bring in all the form contents.
section Scripts {
<script>
function confirmEdit() {
swal({
title: "MIS",
text: "Case Created your Case Number is " + $("#Id").val(),
icon: "warning",
buttons: true,
dangerMode: true,
}).then((willUpdate) => {
if (willUpdate) {
$.ajax({
url: "/tests/edit/" + $("#Id").val(),
type: "POST",
data: {
Id: $("#Id").val(),
Name: $("#Name").val()
},
dataType: "html",
success: function () {
swal("Done!", "It was succesfully edited!", "success")
.then((success) => {
window.location.href = "/tests/index"
});
},
error: function (xhr, ajaxOptions, thrownError) {
swal("Error updating!", "Please try again", "error");
}
});
}
});
}
</script>
}
asp.net core will automatically bind json data using the [FromBody] attribute.
data: {
id: $("#Id").val(),
name: $("#Name").val()
},
and then in your controller
[HttpPost("/tests/edit/")]
public IActionResult Process([FromBody] MyData data){ ... }
where MyData is
public class MyData
{
public string Id {get;set;}
public string Name {get;set;}
}
section Scripts { function confirmEdit() {
swal({ title: "MIS", text: "Case Created your Case Number is " + $("#Id").val(), icon: "warning", buttons: true, dangerMode: true, }).then((willUpdate) => { if (willUpdate) {
var obj = { Id: $("#Id").val(), Name: $("#Name").val() }
$.ajax({ url: "/tests/edit/" + $("#Id").val(), type: "POST", data: JSON.Stringify(obj), dataType: "html", success: function () { swal("Done!", "It was succesfully edited!", "success") .then((success) => { window.location.href = "/tests/index" }); }, error: function (xhr, ajaxOptions, thrownError) { swal("Error updating!", "Please try again", "error"); } }); } }); } }
in c# use
public ActionResult FormPost(MyData obj)
Please refer to the following methods to submit the form data to action method:
using the serialize() method to serialize the controls within the form.
#model MVCSample.Models.OrderViewModel
<h4>OrderViewModel</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Showsummary" asp-controller="Home" method="post" class="signup-form">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="OrderId" class="control-label"></label>
<input asp-for="OrderId" class="form-control" />
<span asp-validation-for="OrderId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="OrderName" class="control-label"></label>
<input asp-for="OrderName" class="form-control" />
<span asp-validation-for="OrderName" class="text-danger"></span>
</div>
<div id="packages">
#for (int i = 0; i < Model.Packages.Count; i++)
{
<div class="form-group">
<label asp-for="#Model.Packages[i].Pid" class="control-label"></label>
<input asp-for="#Model.Packages[i].Pid" class="form-control" />
<span asp-validation-for="#Model.Packages[i].Pid" class="text-danger"></span>
<br />
<label asp-for="#Model.Packages[i].PackageTitle" class="control-label"></label>
<input asp-for="#Model.Packages[i].PackageTitle" class="form-control" />
<span asp-validation-for="#Model.Packages[i].PackageTitle" class="text-danger"></span>
</div>
}
</div>
</form>
</div>
</div>
<div>
<input type="button" id="summary" value="Summary" />
<div id="page_3">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function () {
$("#summary").click(function () {
console.log("calling summary");
event.preventDefault();
$.ajax({
type: "POST",
url: "/Home/Showsummary", //remember change the controller to your owns.
data: $("form.signup-form").serialize(),
success: function (data) {
console.log(data)
},
failure: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
});
});
});
</script>
Code the the action method:
[HttpPost]
public PartialViewResult Showsummary(OrderViewModel model)
{
try
{
//...
return PartialView("OrderSummary", model);
}
catch
{
return PartialView("OrderSummary", model);
}
}
After clicking the button, the result like this:
As we can see that, we could get the element's value in the form and even the nested entity.
Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.
Create a JavaScript object, and post it to action method.
Change the JavaScript script as below:
$(function () {
$("#summary").click(function () {
console.log("calling summary");
event.preventDefault();
//create a object to store the entered value.
var OrderViewModel = {};
//using jquery to get the entered value.
OrderViewModel.OrderId = $("input[name='OrderId']").val();
OrderViewModel.OrderName = $("input[name='OrderName']").val();
var packages = [];
//var count = $("#packages>.form-group").length; //you could use it to check the package count
$("#packages>.form-group").each(function (index, item) {
var package = {}
package.Pid = $(item).find("input[name='Packages[" + index + "].Pid']").val();
package.PackageTitle = $(item).find("input[name='Packages[" + index + "].PackageTitle']").val();
packages.push(package);
});
//add the nested entity
OrderViewModel.Packages = packages;
$.ajax({
type: "POST",
url: "/Home/Showsummary", //remember change the controller to your owns.
data: OrderViewModel,
success: function (data) {
console.log(data)
$('#page_3').html(data);
},
failure: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
});
});
});
By using the above code, I could also get the submit entity, you could refer to it.
Hi i want to post just a simple string to a controller action in asp.net mvc5.
Im trying to do this for hours and cant find a solution on how it works.
I have tried many different solutions without one of them working in how I want.
For hours...
I have a simple view:
#{
ViewBag.Title = "Rollen und Rechte";
}
<form>
<table cellpadding="5">
<tr>
<td>Rollenname:</td>
<td><input type="text" name="Name" id="roleNameVal" />Rollenname</td>
</tr>
</table>
<br />
<label id="resultLabel"></label>
<input type="submit" value="Submit" id="btn_click" />
<div id="mydiv"></div>
</form>
#section scripts {
<script type="text/javascript">
$('#btn_click').click(function ()
{
alert("jas");
var val1 = $('#roleNameVal').val();
$.ajax({
type: "post",
url: "/Create/Role",
data: { "val1": val1 },
success: function (data) {
alert(data);
}
})
}
</script>
}
The thing is that the function is never called.
What is wrong here?
And... in the next step I want to update div id mydiv
How can I change that without return a complete view in the controller and force a reload?
Thanks in advance :)
You are missing a closing parenthesis right before your closing </script> tag:
<script type="text/javascript">
$('#btn_click').click(function ()
{
alert("jas");
var val1 = $('#roleNameVal').val();
$.ajax({
type: "post",
url: "/Create/Role",
data: { "val1": val1 },
success: function (data) {
alert(data);
}
})
}**)**
</script>
instead of using button click event use the following
$(document).on("submit", "form", function (event) {
alert("jas");
var val1 = $('#roleNameVal').val();
$.ajax({
type: "post",
url: "/Create/Role",
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data) {
alert(data);
},
error: function (xhr, desc, err) {
}
})
}
you can use ajax.BeginForm of mvc
like this :
#using (Ajax.BeginForm("YourActionName", "YourControllerName", new AjaxOptions {
InsertionMode = InsertionMode.Replace, //target element(#mydiv) will be replaced
UpdateTargetId = "mydiv"
}))
{
<table cellpadding="5">
<tr>
<td>Rollenname:</td>
<td><input type="text" name="Name" id="roleNameVal" />Rollenname</td>
</tr>
</table>
<br />
<label id="resultLabel"></label>
<input type="submit" value="Submit" id="btn_click" />
}
<div id="mydiv"></div>
and in yourController :
public PartialViewResult YourActionName(string name)
{
return PartialView("_YourPartialView");
}
_YourPartialView is a partial View that you want to return replace it with "mydiv" And how to make it with VIEW is the same
if your partial view has a model you should do this :
return PartialView("_YourPartialView",yourModel);
Here is my jquery code:
<script type="text/javascript">
$("#submitfileform").submit(function () {
$.ajax({
type: 'POST',
contentType: 'application/html;charset=utf-8',
dataType:'html',
success:function (result) {
$('#tablepartialview').html(result);
},
error:function (xhr, status) {
alert(status);
}
})
});
</script>
and here is html.beginform,
#using (Html.BeginForm("PropertyColumnMap", "ImportFile", FormMethod.Post, new { enctype = "multipart/form-data", #class = "form single-col",id="submitfileform"}))
{
<input type="file" name="uploadFile" id="uploadFile" value=""/>
<select id="assetlist" name="assetlist">
<option>...</option></select>
<input class="btn btn-primary" type="submit" value="Submit" id="submitfile"/>
}
<div id="tablepartialview">
</div>
What happens is, on submit, I get the partial view of the same page 'Index' in div-'tablepartialview', instead of another page 'PropertyColumnMap', which I want. After the ajax call is done,it redirects to action 'PropertyColumnMap', and then I get the view for PropertyColumnMap.
public ActionResult PropertyColumnMap(FormCollection f, HttpPostedFileBase uploadFile)
{
String fileid = Import(uploadFile);
var excel = new ExcelQueryFactory(Session[fileid].ToString());
excel.DatabaseEngine = DatabaseEngine.Ace;
var workSheetName = excel.GetWorksheetNames().Last();
var assetname = f["assetlist"].ToString();
Mapping(assetname, workSheetName, fileid);
return PartialView("PropertyColumnMap");
}
If its possible please include following js to your project
http://malsup.github.com/jquery.form.js
Then you can use
$("#submitfileform").ajaxSubmit({
type: 'POST',
success:function (result) {
$('#tablepartialview').html(result);
},
error:function (xhr, status) {
alert(status);
}
});
As you are using MVC, just switch your Html.BeginForm to use the Ajaxified Ajax.BeginForm instead.
It allows for many options including specifying the id of the target element to update (e.g. 'tablepartialview').
e.g.
#using (Ajax.BeginForm("PropertyColumnMap", "ImportFile", new AjaxOptions(){ HttpMethod = "POST", UpdateTargetId = "tablepartialview"}, new { enctype = "multipart/form-data", #class = "form single-col", id = "submitfileform" }))
{
<input type="file" name="uploadFile" id="uploadFile" value="" />
<select id="assetlist" name="assetlist">
<option>...</option>
</select>
<input class="btn btn-primary" type="submit" value="Submit" id="submitfile" />
}
<div id="tablepartialview">
</div>
You probably have to install the Ajax unobtrusive NuGet package to provide the wiring, but it is quite simple and does not require you to write any extra JQuery for the view.