#{
var db = Database.Open("CMS");
//retrieving the username of the user from the session
var session_username = Session["session_username"];
//get the details of the user from the database
var getuserdetailscommand = "SELECT * from student where student_username = #0";
var getuserdetailsdata = db.Query(getuserdetailscommand, session_username);
var statusfirstname = "";
var statuslastname = "";
var statusavatar = "";
foreach(var row in getuserdetailsdata){
statusfirstname = row.student_firstname;
statuslastname = row.student_lastname;
statusavatar = row.student_avatar;
}
//on submit execute the following queries
if(IsPost){
if(Request["button"] == "sharestatus"){
//retrieve the data from the form input fields
var statusbody = Request.Form["statusbody"];
var statususername = session_username;
//insert the status for the username into the database
var insertcommand = "INSERT into status(status_body, status_date, status_username, status_firstname, status_lastname, status_avatar) VALUES (#0, #1, #2, #3, #4, #5)";
db.Execute(insertcommand, statusbody, DateTime.Now, session_username, statusfirstname, statuslastname, statusavatar);
}
}
}
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
function get() {
$.post('statusupdateform.cshtml', { name: form.name.value }
}
</script>
<form class="status-form" role="form" action="" enctype="multipart/form-data" method="post" name="form">
<div class="form-body">
<div class="form-group">
<textarea class="form-control" placeholder="What's on your mind?" name="statusbody"></textarea>
</div>
</div>
<div class="form-footer">
<div class="pull-right actions">
<button class="btn btn-primary" name="button" value="sharestatus" onclick="event.preventDefault();get();return false;">Share</button>
</div>
</div>
</form>
This is the code in my cshtml file. I want to submit the form using ajax so that the whole page doesn't get refreshed everytime a user submits anything.
The C# code necessary to run the form is also provided in the code.
Any help how can I submit the for using ajax?
Thank you!
Use Javascript or JQuery for this.
E.g. add script tag with link to jquery code file and then use $.get or $.post to make ajax call.
You should remove
method="post"
From the form as this will make the full page submit. Also you can find more information on how to do this in the Jquery documentation.
See the bottom of this link for an example:
http://api.jquery.com/jquery.post/
Use This to perform your operations
$.ajax
({
url: " URL",
data: "{ 'name' : 'DATA'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
async: true,
dataFilter: function (data) { return data; },
success: function (data)
{
alert(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error");
}
});
Related
Thanks in advance.
I am working on a product filter view similar to some thing like on amazon. where I have refresh multiple views but the data for all the partial view come from single ajax call how to refresh multiple partial view. I can refresh main content area completely but some partial views are not supposed to be refreshed.
I broke it down into steps so you can follow/modify and add your partials like here. First, add 3 Partial Views, they have the same code like below,
#model int
<div class="container fluid">
<h1>PartialDemo#(Model)</h1>
<h3>The views will all update when you click update button below</h3>
</div>
DashboardWidgets.cshtml, the code like below, whatever your csthml page is
//<div class="row-fluid">
// <div class="col">
<div id="WidgetID_1" class="container">
#Html.Partial("_PartialWidget1", 1)
</div>
<div id="WidgetID_2" class="container">
#Html.Partial("_PartialWidget2", 2)
</div>
<div id="WidgetID_3" class="container">
#Html.Partial("_PartialWidget3", 3)
</div>
<div id="WidgetID_4" class="container">
#Html.Partial("_PartialWidget3", 4)
</div>
//</div> // the col
//</div> // the row
// lcik below button to update the partials above
// ***** One button will update them all like you wanted
<button type="button" onclick="UpdateMyWidgets()" class="btn btn-primary">Update All Partial View Views</button>
#section scripts{
<script type="text/javascript">
// this one button will update all your partials/widgets, you can add more partials in this function and just copy paste.
function UpdateMyWidgets() {
$.ajax({
url: "#Url.Action("Widget1")", // whom to call
type: "POST",
datatype: "HTML",
success: function (data) {
$("#WidgetID_1").html(data); // tell it which div to append on return
}
})
$.ajax({
url: "#Url.Action("Widget2")",
type: "POST",
datatype: "HTML",
success: function (data) {
$("#WidgetID_2").html(data);
}
});
$.ajax({
url: "#Url.Action("Widget3")",
type: "POST",
datatype: "HTML",
success: function (data) {
$("#WidgetID_3").html(data);
}
});
}
</script>
}
When click the "Update All Partial View Views" button, it will call "Update" method. If success, the return data will replace div's content
Backend action ajax request.
// these actions get called from the Update Buttons
public ActionResult Widget1()
{
return PartialView("_PartialWidget1", 11);
}
public ActionResult Widget2()
{
return PartialView("_PartialWidget2", 21);
}
public ActionResult Widget3()
{
return PartialView("_PartialWidget3", 31);
}
I'm struggling to get a file to upload. I've checked a dozen samples here (copied code verbatim) and nothing works. I get no errors, no upload, I just get nothing.
I set a breakpoint in my controller but it doesn't get hit. All my code is below, what am I doing wrong
I'm using asp.net.core 2.2 and VS2019
HTML
<div class="card">
<div class="card-header">
<div class="row">
<div class="col">
<h4>Import Users</h4>
</div>
<div class="col">
<form id="frmUpload" action="#Url.Action("PerformImportUsers","Admin")" method="post">
#Html.AntiForgeryToken()
<div class="input-group">
<div class="custom-file">
<input type="file" class="custom-file-input" name="importFile" id="inputGroupFile02">
<label class="custom-file-label" for="inputGroupFile02" style="overflow:hidden;">Choose file</label>
</div>
<div class="input-group-append">
<span class="fa fa-upload"></span>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
JS
<script>
$("#uploadFile").on("click", function (e) {
e.preventDefault();
//e.stopPropagation();
debugger;
var myForm = $("#frmUpload");
var sUrl = myForm.attr("action");
var files = $("#inputGroupFile02").get(0);
var formData = new FormData();
for (var i = 0; i != files.length; i++) {
formData.append("myfile", files[i]);
}
$.ajax({
type: "POST",
url: sUrl,
contentType: false,
processData: false,
data: formData,
success: function (result) {
var data = jQuery.parseJSON(result);
showNotify(data.message);
},
error: function () {
alert("there was an error");
}
});
});
</script>
CONTROLLER
[HttpPost]
//[ValidateAntiForgeryToken]
public JsonResult PerformImportUsers(List<IFormFile> importFile)
{
return new JsonResult(new { result = "success", message = "Uploaded" });
}
To upload a file your form tag needs enctype="multipart/form-data"
Try adding that and you should see the file come through in the back end.
And remove that javascript, that is not needed.
[HttpPost]
//[ValidateAntiForgeryToken]
public JsonResult PerformImportUsers() // remove parameter
{
var files = this.Request.Form.Files; //retreive files
return new JsonResult(new { result = "success", message = "Uploaded" });
}
Besides this code below will only add 1 file
for (var i = 0; i != files.length; i++) {
formData.append("myfile", files[i]); // change it to "myfile"+i
}
First of all, press F12 in browser to check the action (sUrl) is correct or not,it should be action="/Admin/PerformImportUsers".
Then change your js to below to upload files using formdata.You need to match name of formData to the parameter name (importFile)on POST method.
<script>
$("#uploadFile").on("click", function (e) {
e.preventDefault();
var myForm = $("#frmUpload");
var sUrl = myForm.attr("action");
var input = document.getElementById("inputGroupFile02");
var files = input.files;
var formData = new FormData();
for (var i = 0; i != files.length; i++) {
formData.append("importFile", files[i]);
}
$.ajax({
type: "POST",
url: sUrl,
contentType: false,
processData: false,
data: formData,
success: function (result) {
var data = jQuery.parseJSON(result);
showNotify(data.message);
},
error: function () {
alert("there was an error");
}
});
});
</script>
I have a html form in which I write in a text box and submit when press a button and it saves in db but I want the page not to refresh and continue with the values in the text box
I have see people talking about ajax but I have never worked with ajax
<div class="row" style="float:left; margin: 2px ">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="col-md-3">
<div class="form-group">
<label>Pressão Injeção:</label>
<input id="id3" type="text" name="Pressão_de_Injeção" /> <br />
</div>
</div>
Here is a quick example of an AJAX call which will POST data to an controller:
var menuId = $("ul.nav").first().attr("id");
var request = $.ajax({
url: "Home/SaveForm",
type: "POST",
data: {id : menuId},
dataType: "html"
});
request.done(function(msg) {
console.log('success');
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
Note, that you can also pass objects to the controller by supplying them as an variable within the data object:
var menuId = $("ul.nav").first().attr("id");
var obj = {
id: menuId,
text: "Foo"
};
var request = $.ajax({
url: "Home/SaveForm",
type: "POST",
data: {name: "Jim", object: Obj},
dataType: "html"
});
(Code adapted from an answer by apis17.)
An introduction to AJAX, can be found here:
https://www.w3schools.com/js/js_ajax_intro.asp
The only other method of performing what you required (without using AJAX) is to use a form submit and pass the data back to the HTML form once complete. You would then need to re-populate the fields (however, this will cause additional work on both submitting and re-populating, if (and/or when) new fields are adding if the future).
You will have to take the ajax approach.
But if you don't want to do that, you can always post to the controller and return the model to the view. It will have the text you entered into the textbox.eg.
public IActionResult MyView()
{
return View();
}
[HttpPost]
public IActionResult MyView(MyModel model)
{
return View(model);
}
Hope this helps as an alternative.
I have a webpage where many section of the page gets loaded using jQueryAjax after intial load. Now I need to download the web page completey using C#. It should be downloaded once all the ajax call completes.
I tried many ways to do that but didnot get through. Can sombody suggest the best way to handle that?
I have my MVC view like this
#{
ViewBag.Title = "My Page";
}
<div id="Banner" class="divMain" style="height: 92px;" style="margin-left: 0.3em">
</div>
<div style="float:left; width:99.6%">
<div id="StockPriceCharts" class="div_Chart" style="margin-top:0.1em;margin-left:-0.1em">
</div>
<div id="Rating" class="divMain_48" style="margin-left: 0.3em; min-height:140px">
<div class="ControlHeader">
Entity Details</div>
<div id="dvEntity" >
</div>
</div>
<div id="FilMeetings" class="divMain_48" style="float:left;">
<div class="ControlHeader">
MEETINGS
</div>
<div id="dvMeeting" style="height: 119px;" class="loading">
</div>
</div>
</div>
<span>
<input id="IdHidden" type="hidden" value="#ViewBag.SymbolId"/>
</span>
<script type="text/javascript">
$.ajaxSetup({ cache: false });
// For Entity Detail
$.ajax({
url: '/HomePage/Entity Detail/' + $('#IdHidden').val(),
contentType: 'application/html; charset=utf-8',
type: 'GET',
dataType: 'html',
data: { symbolId: document.getElementById("IdHidden").value }
})
.success(function (result) {
$('#dvEntity').html(result);
})
.error(function (xhr, status) {
$('#dvEntity').html('<div style="height:40px;" class="loading">Failed to load Entities</div>');
});
$.ajax({
url: '/HomePage/GetMEETINGSs/' + $('#IdHidden').val(),
contentType: 'application/html; charset=utf-8',
type: 'GET',
dataType: 'html',
data: { symbolId: document.getElementById("IdHidden").value }
})
.success(function (result) {
$('#dvMeeting').html(result);
})
.error(function (xhr, status) {
$('#dvMeeting').html('<div style="height:40px;" class="loading">Failed to load Business description</div>');
});
</script>
I have removed some part and put dummy value for brevity. But I have similar more section that are getting loaded via AJAX and there are some static content as well. When I download it ajax section is not getting loaded.
If I understand you right, after page loaded you're loading data with ajax and rendering it with JavaScript.
If so, you have to implement data rendering in Razor way (If you're using ASP.NET MVC). Each section should have own partial view. Create a new View and put Partials in it.
public ViewResult Index()
{
var api = new YouWebApiController();
var sectionData_1 = api.GetSectionData_1();
var sectionData_2 = api.GetSectionData_2();
var sectionData_3 = api.GetSectionData_3();
ViewBag.SectionData_1 = sectionData_1;
ViewBag.SectionData_2 = sectionData_2;
ViewBag.SectionData_3 = sectionData_3;
return new View();
}
In your view:
<body>
#Html.RenderPartial("SectionPartial_1", ViewBag.SectionData_1);
#Html.RenderPartial("SectionPartial_2", ViewBag.SectionData_2);
#Html.RenderPartial("SectionPartial_3", ViewBag.SectionData_3);
</body>
I have managed to get a JQuery autocomplete working in C#.net using a webservice.
Here is the asp code:
<div class="row">
<div class="span4">
<h3>
Manage Season</h3>
</div>
</div>
<div class="row">
<div class="span2">
<p>
<label class="control-label" for="TeamName">
Team Name:</label></p>
</div>
<div class="span3">
<asp:TextBox ID="TeamNameTextBox" runat="server" CssClass="searchinput"></asp:TextBox>
<asp:Button ID="AddTeamButton" CssClass="btn btn-primary" runat="server" Text="Add"
OnClick="AddTeamButton_Click" />
</div>
<script type="text/javascript">
$(document).ready(function () {
$(".searchinput").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "PredictiveSearch.asmx/GetAllPredictions",
data: "{'keywordStartsWith':'" + request.term + "'}",
dataType: "json",
async: true,
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Due to unexpected errors we were unable to load data");
}
});
},
minLength: 1
});
});
</script>
And the c# web service:
[System.Web.Script.Services.ScriptService]
public class PredictiveSearch : System.Web.Services.WebService
{
[WebMethod]
public IList<string> GetAllPredictions(string keywordStartsWith)
{
//TODO: implement real search here!
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["RaiseFantasyLeagueConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("[dbo].[findEnglishTeams]", conn);
cmd.CommandType = CommandType.StoredProcedure;
string searchTerm = keywordStartsWith;
SqlParameter searchTermParam = new SqlParameter("#searchterm", searchTerm);
cmd.Parameters.Add(searchTermParam);
IList<string> output = new List<string>();
conn.Open();
SqlDataReader dReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dReader.HasRows)
{
while (dReader.Read())
{
output.Add(dReader["englishTeamName"].ToString());
}
return output;
}
else
{
return output;
}
}
}
I need to get the ID of the values i am populating the drop down with, how is this possible?
Since you are populating this on the Client Side using an Ajax request, you are going to have to either:
Get the selected value by writing it to a html input type=hidden element and reading it on the server side when the form posts back. Just don't forget to make the input type=hidden element a server-side control by adding runat="server"
Submit the selected value via another Ajax request.
Read the selected values using the Request.Params collection, using the listbox's name as the Key. Something like:
var selectedValues = Request.Params["select_box_name"];
You won't be able to simply use ListBox.SelectedValue because the values won't be found in the ViewState since you are populating it via Ajax.
I'd go with option 3...
Hope the something like this serves your need better