Clear the values on a webform after submitting - c#

I have a webform with few textboxes and dropdownlists, and a submit button
when the user clicks the submit button im sending the form values to the controller with an ajax call and from controller to model to database
after submitting the form values are still being displayed in the respective textboxes.
i also have a output parameter with my procedure, if the data is successfully submitted then i will get output parameter value as 1 else 0
so based on this output parameter value from the controller i should be able to clear the form values, if the insertion fails the values should be displayed
how to achieve it?
<script type="text/javascript">
function CreateUser() {
$.ajax({
url: '#Url.Content("~/User/CreateUser")',
data: { My Data },
type: 'GET',
success: function (data) {
alert(data);
}
});
}
$('#btnCreate').click(function () {
CreateUser();
});
</script>
Code:
public ActionResult RegisterUser(Users objUser)
{
//i have done some code here to bind dropdownlists from database etc
return View(objUser);
}
public ActionResult CreateUser(str Uname)
{
try
{
Users objUser = new Users();
int Successval = objUser.CreateUser(Uname);
}
catch (Exception ex)
{
}
return RedirectToAction("RegisterUser");
}

try this ...
after you get value 0 then just call below line
document.getElementById("YOUR_FORM_ID").reset();
Update
View :
<form id="myform">
...
</form>
Javascript :
function CreateUser() {
$.ajax({
url: '#Url.Content("~/User/CreateUser")',
data: { My Data },
type: 'GET',
success: function (data) {
if(data == 0)
{
document.getElementById("myform").reset();
}
}
});
}

Related

MVC action controller not rendering the page

after a compiling a form needed for register on the website( Registration.cshtml ), the form data are sent in a sqlite db ( successfully). Returning from that, i want to be sent to a Main.cshtml webpage. The problem is that the Action controller that is suposed to render the Main.cshtml view, isn't doing it.
I've tryed changing the Redirect/RedirectToAction and View methods many times, but it was a failure.
return View("Main");
return RedirectToAction("Main");
return JavaScript("window.location = window.location.origin + /Pages/Main");
PagesController.cs
[HttpPost]
public ActionResult Register {
if (insert data in db == true) {
return RedirectToAction("Main");
}
return View();
}
public ActionResult Main(){
return View();
}
Main.cshtml
#{
Layout = "~/Views/Layouts/LoggedMasterPage.cshtml";
ViewBag.Title = "Benvenuto in ETL365";
}
#section Head{
<link rel="stylesheet" href="~/Content/Main.css" />
<script type="text/javascript" src="~/Scripts/Main.js"></script>
}
Part of my Register.js
$("#register").dxButton({
text: "Registrati",
type: "normal",
hint: "Clicca per registrarti",
onClick: function () {
if($('#password').
dxValidator('instance').validate().isValid &&
$('#email').dxValidator('instance').validate().isValid) {
let email = $("#email").dxTextBox('instance').option('value');
let pass = $("#password").dxTextBox('instance').option('value');
$.ajax({
url: window.location.origin + '/Pages/Register',
type: "POST",
data: '{"email":"' + email + '","password":"' + pass + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
});
}
}
});
I've already used breakpoints on Main.cshtml, and it actually gets in there after the
return View();
done by the action Main().
What i expect is to be redirected to the mylocalhost:xxxx/Pages/Main
What i get is absolute nothing, I'm always in mylocalHost:xxxx/Pages/Register
You need to redirect to your main page after a successfull ajax call.
$.ajax({
...
success:
{
location.href = 'mylocalhost:xxxx/Pages/Main'
}
...
You cannot use RedirectToAction for AJAX call response because AJAX requests are intended to update the view without reloading whole page. You need to pass the URL as JSON response like this:
[HttpPost]
public ActionResult Register(string email, string password)
{
if (condition) // put your condition here
{
return Json(new {
status = "Success",
url = Url.Action("Main", "Pages")
});
}
// since this controller receives AJAX request, the partial view should be used instead
return PartialView("_Register");
}
Then in AJAX success condition you can check response status and redirect to target URL:
$.ajax({
url: '#Url.Action("Register", "Pages")',
type: "POST",
data: { email: email, password: pass },
success: function (result) {
if (typeof result.status !== undefined && result.status == "Success") {
location.href = result.url; // redirect to main page
}
else {
$('#register').html(result); // refresh partial view
}
}
});
Related issue:
return url.action as json object mvc

How to pass the list of items from stored procedure through ajax or html data

From my Controller i do have the process of list output through the stored procedure that came from Entity Framework (edmx) :
Controller Side:
[HttpPost]
public ActionResult DeleteApprovalTransferNo(string selectedOption)
{
if (selectedOption.Equals("transferList")){
try
{
var output = deleteApprovalSrv.GetPendingTrfApprovalList(Convert.ToDecimal(SessionUserInfo.CurrentBranchCode));
return Json(output, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(ex.ToString());
}
}
}
HTML :
<input type="radio" name ="selectList" value="transferList" /> Transfer No
<input type="radio" name ="selectList" value="rcrList" /> Rcr No
<button type="button" class="btn btn-dark btn-xs g-mt-minus-2" id="LoadBtn"><i class="material-icons">launch</i></button>
Scripting :
<script>
$("#LoadBtn").click(function () {
var selectedOption = $("input:radio[name=selectList]:checked").val()
if(selectedOption == "transferList") {
$.ajax({
url: '/#Controller/DeleteApprovalTransferNo',
type: 'POST',
contentType: 'application/json',
dataType: 'JSON',
data: JSON.stringify({ selectedOption: selectedOption }),
success: function (response) {
if (response != null) {
alert(response);
}
},
error: function (response) {
alert(response);
}
});
}
else {
alert(selectedOption);
}
});
How to pass the list of items from controller local variable named "Output" to HTML process using ajax function. So that i can deliberate those data in each table in the view model.
The stored procedure result with different parameter string,int, decimal.
How can i store it from the list output of the service process to ajax function then deliberate each data from different HTML attributes such as table data

Redirect from partial view to view with json data object

I have a json data object which i need to pass from partial view to view with REDIRECT.
Lets say below is my partial view ( _createEmp.cshtml ):-
Note:- This partial view is in different view or page
<script type="text/javascript">
$(document).ready(function () {
LoadData();
});
function LoadData() {
$.ajax({
type: "GET",
url: baseURL + "Employee/GetEmpInfo",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data) {
console.log(data);
**EmpData** = data; // EmpData object
},
error: function (error) {
console.log("Error: " + error);
}
});
}
</script>
<div>
<input type="submit" value="Save" onclick="SetEmpInfo()" />
</div>
And i want to transfer EmpData object to a different view (lets say NewEmp.cshtml), bind something in that view from passed "EmpData object" and open that view (or REDIRECT to view NewEmp.cshtml).
As you are using ajax, you could return the URL from your action and have it redirected in javascript.
Without seeing your controller action you would need to do something like this:
Controller
public ActionResult GetEmpInfo()
{
// Do stuff
return Json(new { success = true, redirecturl = Url.Action("GetEmpInfoSuccess") });
}
Then add something like this to your success handler in javascript:
Javascript (within your success handler)
success: function (data) {
if (data.success == true)
{
window.location = result.redirecturl;
}
}
Issuing a request to Employee/GetEmpInfo for getting the data and on success redirecting to other view - doesn't sound right
I think that you can do all this with one trip to server:
Write an Action that receives all the the parameters that GetEmpInfo receives. Lets call it NewEmployee.
If GetEmpInfo action is your code, reuse it's logic inside NewEmployee action to get EmpData. If it is not your code, you can use issue async request with HttpClient and get EmpData - All this performed on the server
Once you have EmpData you should have everything your need to return a NewEmp view.
In this particular case there is no need in AJAX at all. You can use regular form submit in case that you need to post some data or just a redirect to NewEmployee action.

How to pass a JavaScript Array to ASP.Net MVC Action as part of post

I have a cshtml as follow,
DoPost.cshtml
#using (Html.BeginForm("Purchase", "PurchaseOrder", FormMethod.Post, new { #id = "frmPurchase" }))
{
// statements
// statements
<input type="button" id="submitPurchase" onclick = "myPurchase()" value="Select" />
}
In Javascript I have an array strings in variable "ExtraItems"
ExtraItems[0] ="123"
ExtraItems[1] ="124"
ExtraItems[2] ="125"
My Action which accept the data is as follows,
public ActionResult Purchase(PurchaseOrderModel model)
{
//Do some stuff with the passed data
return View("Purchase", model);
}
In the above PurchaseOrderModel, I have the property
public string[] SelectedProducts { get; set; }
to accept the Javascript Array elements.
What I tried:
The simple post did not work as the JavaScript array elements are not part of the Form elements,I couldn't use a #Html.HiddenFor because it is an array.
Hence tried to do an Ajax post under function myPurchase(),
$a.post('#Url.Action("Purchase", "PurchaseOrder")', { SelectedProducts: ExtraItems });
Here I did not get the ExtraItems details under model.SelectedProducts in the action. The biggest issue was i wanted to load the Purchase.cshtml View from the action, instead I got the controll back to the Jquery Post.
Please help me how can I solve this.
You should post your javascript array as a json object. You use the JSON.stringify() method converts a value to JSON. Something like :
$.ajax({
url: '#Url.Action("Purchase", "PurchaseOrder")',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
SelectedProducts: ExtraItems
})
});
Here is my example for solving your issue
-----------------------------------------
//Script
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script>
var ExtraItems = ["aa","bb","cc","ff"];
function a()
{
$.ajax( {
type: 'POST',
url: '/Default1/Index',
data: { SelectedProducts: ExtraItems },
traditional: true,
success: function ( response )
{
alert( 'Sucs' );
}
} );
}
</script>
<button onclick="a();">click</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
//Controller
[HttpPost]
public ActionResult Index( string[] SelectedProducts )
{
return View();
}
Take a string property in your model and then send the data as comma separated string
var dataToSent = ExtraItems.join(',')
If you have a property named Datum of type string in your model Purchase then the data to be sent will be, passing model
data : 'Datum=' + dataToSent
In your action you can split data into array
also for return response you have to redirect the page in the success function of your ajax call
$.ajax( {
type: 'POST',
url: '/Default1/Index',
data: { SelectedProducts: ExtraItems },
traditional: true,
success: function ( response )
{
window.location.href = "/controller/action" <--your url
}
} );
Use $.ajax function with the option traditional:true for enabling ASP.NET MVC default model binding for the list of string items.

jQuery AutoComplete - Return multiple values

I'm using jQuery AutoComplete, and I have an auto-complete search box to search for users.
Default.aspx
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#<%= txtUser.ClientID %>").autocomplete('UsersAutoComplete.ashx');
});
</script>
<asp:TextBox ID="txtUser" runat="server" />
UsersAutoComplete.ashx
public class UsersAutoComplete : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
List<User> users = DataContext.Users
.Where(u => u.Username.StartsWith(context.Request.QueryString["q"]))
.Take(Int32.Parse(context.Request.QueryString["limit"]))
.OrderBy(u => u.Username)
.ToList();
foreach (User user in users)
{
context.Response.Write(user.Username + Environment.NewLine);
}
}
public bool IsReusable
{
get { return false; }
}
}
As you can see, it only returns the Username. I'd also like to return the user's UserID as well.
The results will still only show a list of Usernames, but when someone selects a user, I'd like to store the UserID for that user in a hidden value so that I can do whatever I need to with it. I'll be running a query on the selected user, and I'd rather lookup the user by UserID than by Username.
Is there a way to do this?
I would create a class that contains the values you want returned. Then create a new instance of that class with the values and serialize the response using JSON.
That should be enough to get you pointed in the right direction.
EDIT: Here is how I do it.
$("#<%= txtUser.ClientID %>").autocomplete(
{
source: function (request, response) {
$.ajax(
{
url: autocompleteSourceUrl,
dataType: "json",
type: "POST",
data: { LookupPrefix: request.term, TotalResults: 10 },
success: function (data) {
response($.map(data.LookupItems,
function (item) {
var itemLabel = item.DisplayName;
if (itemLabel.length > 37)
itemLabel = itemLabel.substring(0, 37) + "...";
return { label: itemLabel, value: item.DisplayName, data: item }
}))
}
});
},
minLength: 3,
select: function (event, ui) {
selectedItemData = ui.item.data;
}
});
This is how I setup the autocomplete with the custom class returned. My class being returned has the following structure:
{ Id: int, DisplayName: string }
Notice also the select function. That stores an internal reference to the data item that was returned. So when I need to submit that info I can just look at the selectedItemData and use all the properties of the class at that time as well.
I hope this helps a little more. But the part for you to work with would be in the success method where I assign the object to the item.

Categories