How to combine between the script and the action in the button - c#

I am developing an ASP .Net MVC 3 application using C# and SQL Server 2005.
In a view, I have a button which I add in it a JQuery Script.
This button has as purpose to save some values in a list.
The problem that the button works perfectly but when i add the Script, the situation change and the button didn't works and became static (dead).
This is the code in the view :
<div>
<input type="submit" value="Enregistrer" id="btnSave" />
</div>
<script type="text/javascript">
$(function () {
$('#btnSave').click(function () {
$('#poste option:selected').remove();
return false;
});
});
</script>
and this is the code of methode save in the controller :
[HttpPost]
public ActionResult Save(FlowViewModel model)
{
Console.WriteLine("" + model.Nbr_Passage);
if (ModelState.IsValid)
{
Gamme G = new Gamme();
G.ID_Gamme = model.SelectedProfile_Ga;
G.ID_Poste = model.SelectedPoste;
//G.Last_Posts = model.PostePrecedentSelected;
G.Next_Posts = model.PosteSuivantSelected;
G.Nbr_Passage = int.Parse(model.Nbr_Passage);
G.Position = int.Parse(model.Position);
((List<Gamme>)System.Web.HttpContext.Current.Session["GammeList"]).Add(G);
var list = ((List<Gamme>)System.Web.HttpContext.Current.Session["GammeList"]);
}
return RedirectToAction("Index");
}

Remove return false; from your script:
$(function () {
$('#btnSave').click(function () {
$('#poste option:selected').remove();
});
});

Related

Return JSON with ajax is giving me blank page with return parameters

I started learning AJAX like this week and I was trying to make a simple voting thingy on page in asp mvc - when you click one button you get message like a popup (in browser) and count increments, when you click second, you get another count decrements, you get the idea.
I wanted to test it's possible to do like voting system (upvotes/downvotes) that will update itself's oount on click without needing to refresh the page.
However, when I click on this buttons, it gets me blank page with the things that return json contains. (picture included at the very bottom of post).
I am most likely missing something obvious, so please bear with me and if you could navigate me where am I wrong, please do.
My Controller:
public IActionResult Privacy()
{
Vote vote = new Vote();
vote.Votes = 0;
return View(vote);
}
[HttpPost]
public ActionResult VoteUp(string plus, string minus)
{
Vote vote = new Vote();
if (plus == null)
{
vote.Votes = vote.Votes -1;
var message = "You voted down";
return Json(new { success = true, message = message }, new Newtonsoft.Json.JsonSerializerSettings());
}
else if ((minus == null))
{
vote.Votes = vote.Votes +1 ;
var messagez = "You voted up";
return Json(new { success = true, message = messagez }, new Newtonsoft.Json.JsonSerializerSettings());
}
else { }
var messagebad = "STH WENT WRONG";
return Json(new { success = true, message = messagebad }, new Newtonsoft.Json.JsonSerializerSettings());
}
My View:
#model JSON_RETURN.Models.Vote
#addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
#{
ViewData["Title"] = "sssss";
}
<form asp-action="VoteUp" asp-controller="Home" method="POST" data-ajax="true">
<div class="form-group"> </div>
<div class="input-group-button">
<button name="plus" class="btn btn-dark" onclick="" value="1" >+</button>
#Model.Votes
<button name="minus" class="btn btn-dark" onclick="" value="-1" >-</button>
</div>
</form>
#section scripts{
<script src="~/lib/ajax/jquery.unobtrusive-ajax.js"></script>
<script src="~/lib/jquery/dist/jquery.js"></script>
<script type="text/javascript">
function SubmitForm(form) {
form.preventDefault();
$.ajax({
type: "POST",
url: "HomeController/VoteUp", //form.action,
data: ('#form'),
success: function (data) {
if (data.success) {
alert(data.message);
} else {
}
},
});
};
</script>
}
My Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace JSON_RETURN.Models
{
public class Vote
{
public int Votes { get; set; }
}
}
And there's the blank page I'm getting every click (message varies ofc):
(https://imgur.com/uVNSmE6)
What you did is just a form submit instead of using ajax. Why it return json string that is because you return json string in your backend code(return Json(new { success = true, message = messagebad }, new Newtonsoft.Json.JsonSerializerSettings());).
I saw you use jquery.unobtrusive-ajax.js in your code, also you create a js function with ajax. Actually, you just need to choose one of the two ways to achieve your requrement.
Here is the correct way of using jquery.unobtrusive-ajax.js :
Note:
1.If you use asp.net core, it contains jquery.js in _Layout.cshtml by default. So when you use #section Scripts{}, no need add the jquery.js again. If your _Layout.cshtml does not contain jquery.js, you need add this js file before jquery.unobtrusive-ajax.js:
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/ajax/jquery.unobtrusive-ajax.js"></script>
2.You need specific data-ajax-update to tell the elements where need to be updated with the AJAX result.
More supported data attributes for jquery.unobtrusive-ajax.js you can refer to here.
View:
#model Vote
#addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
#{
ViewData["Title"] = "sssss";
}
<div id="result"> //add this div...
//add this...
<form asp-action="VoteUp" asp-controller="Home" method="POST" data-ajax-update="#result" data-ajax="true">
<div class="form-group"> </div>
<div class="input-group-button">
<button name="plus" class="btn btn-dark" value="1">+</button>
#Model.Votes
<input hidden asp-for="Votes" /> //add this....
<button name="minus" class="btn btn-dark" value="-1">-</button>
</div>
</form>
</div>
#section scripts{
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ajax-unobtrusive/3.2.6/jquery.unobtrusive-ajax.js" integrity="sha256-v2nySZafnswY87um3ymbg7p9f766IQspC5oqaqZVX2c=" crossorigin="anonymous"></script>
}
Controller:
Note: You can see that I add a hidden input for Votes in form, that is because only input or select type of element can be post to backend. The reason for why I want to get Votes value is because your code always create a new instance for Vote, the value will always plus start with 0.
public IActionResult Privacy()
{
Vote vote = new Vote();
vote.Votes = 0;
return View(vote);
}
[HttpPost]
public ActionResult VoteUp(string plus, string minus)
{
Vote vote = new Vote();
vote.Votes = int.Parse(Request.Form["Votes"]);
if (plus == null)
{
vote.Votes = vote.Votes - 1;
}
else if ((minus == null))
{
vote.Votes = vote.Votes + 1;
}
else { }
return PartialView("Privacy", vote);
}
Result:

Load specific data based on passed Id on link click in ASP.NET

My goal is to build AJAX, which will show details of specific Building when user clicks on specific link <a...>
My Controller
public IActionResult BuildingDetail(int id)
{
return PartialView("_BuildingDetailsPartial", _buildingRepository.GetById(id));
}
My view
#foreach (var employee in Model.employees)
{
...
<a id="LoadBuildingDetail" href="#LoadBuildingDetail" data-assigned-id="#employee.Office.BuildingId"
onclick="AssignButtonClicked(this)">#employee.Office.Name</a>
...
}
Place to show Details of Building when user clicks on link. So _BuildingDetailsPartial will render here.
<div id="BuildingDetail">
</div>
Scripts: Im stuck here. I need to load specific BuildingDetail based on passed id.
<script type="text/javascript">
$(document).ready(function () {
function AssignButtonClicked(buildingId) {
var BuildingId = $(buildingId).data('assigned-id');
}
$("#LoadBuildingDetail").click(function () {
$("#BuildingDetail").load("/employees/buildingdetail/", { id: AssignButtonClicked() }, );
});
})
</script>
The issue is due to the logic of the click handler in jQuery. You're attempting to call a function in the onclick attribute of the element which won't be accessible as it's defined inside the document.ready scope.
Also, you're trying to set the id property of the object you send in the request to a function which has no return value.
To fix this, remove the onclick attribute from the HTML you generate, and just read the data attribute from the element directly in the jQuery event handler before you send the AJAX request. Try this:
#foreach (var employee in Model.employees)
{
<a class="LoadBuildingDetail" href="#LoadBuildingDetail" data-assigned-id="#employee.Office.BuildingId">#employee.Office.Name</a>
}
<script type="text/javascript">
$(function () {
$(".LoadBuildingDetail").click(function () {
$("#BuildingDetail").load("/employees/buildingdetail/", {
id: $(this).data('assigned-id')
});
});
})
</script>

jQueryu ui autocomplete doesn´t show anything in MVC c#

I want to display an autocomplete textbox in a MVC C# View using jQuery-ui autocomplete, this is the code of my view
#{
ViewBag.Title = "Index";
}
<script src ="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" />
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script type="text/javascript">
$(function () {
$("#SearchString").autocomplete({
source: "/Borrar/autocompletar",
minLength: 1,
select: function (event, ui) {
if (ui.item) {
$("#SearchString").val(ui.item.value);
}
}
});
});
</script>
<div class="container col-md-10 col-md-offset-3">
<h2>Autocompletar</h2>
#using (Html.BeginForm())
{
<p>
Empresa: #Html.TextBox("SearchString")
<input type="submit" value="Search" />
</p>
}
</div>
this is the code of the controller that should populate the textbox
public JsonResult autocompletar(string prefix)
{
List<GFC_Site.ViewModels.EmpresaAutocomplete> listado = new List<GFC_Site.ViewModels.EmpresaAutocomplete>();
ProxyGFC.ServiceGFCClient cliente = new ProxyGFC.ServiceGFCClient();
List<WcfService.Entidades.EmpresaAutocomplete> listadoBase = new List<WcfService.Entidades.EmpresaAutocomplete>();
listadoBase = cliente.Autocompletar(prefix);
foreach (var item in listadoBase)
{
GFC_Site.ViewModels.EmpresaAutocomplete dato = new ViewModels.EmpresaAutocomplete();
dato.empresa = item.empresa;
//dato.np = item.np;
listado.Add(dato);
}
return Json(listado, JsonRequestBehavior.AllowGet);
}
where (GFC_Site.ViewModels.EmpresaAutocomplete) is a class with only one string property (empresa) and (ProxyGFC.ServiceGFCClient cliente) is a connection to a WCF Server, the WCF is the one that connects the application with the database and (List listadoBase) is a class in WCF with two properties(empresa and np).
and this is the method in WCF that retrieve the info that I want to display in the textbox
public List<EmpresaAutocomplete> Autocompletar(string prefix)
{
OdbcCommand cmd = Helper.Commandos.CrearComando();
cmd.CommandText = "select numero_patronal, nombre_empresa from empresas where estado= ? and nombre_empresa like ?";
cmd.Parameters.Add("#estado", OdbcType.VarChar).Value = "1";
cmd.Parameters.AddWithValue("#empresa", prefix + "%");
List<EmpresaAutocomplete> data = new List<EmpresaAutocomplete>();
try
{
cmd.Connection.Open();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
EmpresaAutocomplete datos = new EmpresaAutocomplete();
datos.np = reader["numero_patronal"].ToString();
datos.empresa = reader["nombre_empresa"].ToString();
data.Add(datos);
}
}
catch (Exception ex)
{
throw new ApplicationException("Excepcion :", ex);
}
return data;
}
well, my problem is that the textbox doesn´t show anything, actually it gets frozen
could you please tell me what seems for you to be the problem?
First off, let’s take take a look at autocomplete in action, starting with a text input:
<label for=”somevalue”>Some value:</label><input type=”text” id=”somevalue” name=”somevalue”/>
If we add a reference to the jQuery UI script file and css file, we can add a script block to our view:
<script type=”text/javascript” language=”javascript”>
$(document).ready(function () {
$(‘#somevalue’).autocomplete({
source: ‘#Url.Action(“Autocomplete”)’
});
}) </script>
This script block identifies the text input by id and then invokes the autocomplete function to wire up the autocomplete behaviour for this DOM element. We pass a URL to identify the source of the data. For this post I’ve simply created an ASP.NET MVC action that returns JSON data (shown below). Note that in the view I used Url.Action to look up the URL for this action in the routing table – avoid the temptation to hard-code the URL as this duplicates the routing table and makes it hard to change your routing later.
public ActionResult Autocomplete(string term)
{
var items = new[] {“Apple”, “Pear”, “Banana”, “Pineapple”, “Peach”};
var filteredItems = items.Where(
item => item.IndexOf(term, StringComparison.InvariantCultureIgnoreCase) >= 0
);
return Json(filteredItems, JsonRequestBehavior.AllowGet);
}
https://blogs.msdn.microsoft.com/stuartleeks/2012/04/23/asp-net-mvc-jquery-ui-autocomplete/

How to create the confirm box in mvc controller?

I need to create the confirm box in mvc controller?. Using this 'yes' or 'no' value I need to perform the action in my controller. How we do that?
Sample code:
public ActionResult ActionName(passing value)
{
// some code
message box here
if (true)
{ true code}
else { else code}
}
You can do this with ActionLink
#Html.ActionLink(
"Delete",
"DeleteAction",
"Product",
new { confirm = true, other_parameter = "some_more_parameter" },
new { onclick = "return confirm('Do you really want to delete this product?')" })
If user confirm, then link parameter will pass to the controller action method.
public ActionResult DeleteAction(bool confirm, string other_parameter)
{
// if user confirm to delete then this action will fire
// and you can pass true value. If not, then it is already not confirmed.
return View();
}
Update
You can not show message box in controller side. But you can do this like following
public ActionResult ActionName(passing value)
{
// some code
message box here
if (true){ ViewBag.Status = true }
else { ViewBag.Status = false}
return View();
}
And view
<script type="text/javascript">
function() {
var status = '#ViewBag.Status';
if (status) {
alert("success");
} else {
alert("error");
}
}
</script>
But these all codes are not elegant way. This is solution of your scenerio.
Yes, you can do this with #Html.ActionLink as AliRıza Adıyahşi has commented.
Subscribe to the onclick event of the #Html.ActionLink
Here is the implementation:
#Html.ActionLink("Click here","ActionName","ControllerName",new { #onclick="return Submit();"})
And in javascript write the confirm box.
<script type="text/javascript">
function Submit() {
if (confirm("Are you sure you want to submit ?")) {
return true;
} else {
return false;
}
}
</script>
Edit
Try like this:
<script type="text/javascript">
function Submit() {
if (confirm("Are you sure you want to submit ?")) {
document.getElementById('anchortag').href += "?isTrue=true";
} else {
document.getElementById('anchortag').href += "?isTrue=false";
}
return true;
}
</script>
#Html.ActionLink("Submit", "Somemethod", "Home", new { #onclick = "return Submit();", id = "anchortag" })
Now in your controller do some operations based on the isTrue querystring
public ActionResult Somemethod(bool isTrue)
{
if (isTrue)
{
//do something
}
else
{
//do something
}
return View();
}
You dont create confirm box in a Controller, but yes in a View, using JQuery Dialog.
The Controller is already inside the server, so you don't have user interactions there.
Your View, in the other hand, is the place where the user will choose options, type information, click on buttons etc...
You can intercept the button click, to show that dialog, and only submit the post when the option "Yes" gets clicked.
JQuery Dialog requires jquery.js, jquery-ui.js, jquery.ui.dialog.js scripts referenced in your page.
Example:
$(function(){
$("#buttonID").click(function(event) {
event.preventDefault();
$('<div title="Confirm Box"></div>').dialog({
open: function (event, ui) {
$(this).html("Yes or No question?");
},
close: function () {
$(this).remove();
},
resizable: false,
height: 140,
modal: true,
buttons: {
'Yes': function () {
$(this).dialog('close');
$.post('url/theValueYouWantToPass');
},
'No': function () {
$(this).dialog('close');
$.post('url/theOtherValueYouWantToPAss');
}
}
});
});
});
I can confirm that AliRıza Adıyahşi's solution works well.
You can also customize the the message. In my case we're using MVC and Razor, so I could do this:
<td>
#Html.ActionLink("Delete",
"DeleteTag", new { id = t.IDTag },
new { onclick = "return confirm('Do you really want to delete the tag " + #t.Tag + "?')" })
</td>
Which showed a dialog with a specific record named in it. Might also be possible to give the confirm dialog a title, haven't tried that yet.
<a href="#Url.Action("DeleteBlog", new {id = #post.PostId})" class="btn btn-sm btn-danger" onclick="return confirm ('Are you sure want to delete blog?');">
<i class="glyphicon glyphicon-remove"></i> Delete

ASP.NET MVC Form loaded via ajax submits multiple times

I have a partial view containing an ajax form. This partial view is loaded onto my page via an ajax call. I can edit the fields and submit the form and everything works normally. However, if I reload the form N times, the form will submit N times when the save button is clicked.
here is the code for the partial view....
#model blah blah...
<script src="#Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript</script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"type="text/javascript"></script>
<div id="modalForm">
#using (Ajax.BeginForm("Edit", "Info", new{id = Model.UserId}, AjaxOptions{OnSuccess = "infoUpdate" }))
{
//FORM FIELDS GO HERE
<input type="submit" value="Save" />
}
</div>
What am I doing wrong that is causing this behavior?
Each time you reload the form, a trigger is placed for submitting the form. Thus you have n submitting, if you reload the form n times.
Try to load the form only once, if it's possible.
You can try to unbind the submit trigger, when you click on your submit button:
<input type="submit" value="Save" onClick="submitForm()" />
var submitForm = function() {
$("#formAddressShipping form").trigger('submit');
$("#formAddressShipping form").unbind('submit');
return false;
};
Just incase someone is still looking for this - the issue can also occur if you have jquery.unobstrusive js referenced multiple times. For me, I had it in layout and partial. The form got submitted 4 times, may be the field count. Removing the js from partial fixed it. Thanks to this thread ASP.NET AJAX.BeginForm sends multiple requests
Moving this jquery.unobtrusive-ajax.js outside partial solved the issue in my case.
I have faced the same issue and solved it as follows. I have a list. From that list, I call New, Update, Delete forms in UI Dialog. Success will close dialog and will return to list and update the UI. Error will show the validation message and dialog will remain the same. The cause is AjaxForm is posting back multiple times in each submit click.
Solution:
//Link click from the list -
$(document).ready(function () {
$("#lnkNewUser").live("click", function (e) {
e.preventDefault();
$('#dialog').empty();
$('#dialog').dialog({
modal: true,
resizable: false,
height: 600,
width: 800,
}).load(this.href, function () {
$('#dialog').dialog('open');
});
});
//Form submit -
$('#frmNewUser').live('submit', function (e) {
e.preventDefault();
$.ajax({
url: this.action,
type: this.method,
data: $('#frmNewUser').serialize(),
success: function (result)
{
debugger;
if (result == 'success') {
$('#dialog').dialog('close');
$('#dialog').empty();
document.location.assign('#Url.Action("Index", "MyList")');
}
else {
$('#dialog').html(result);
}
}
});
return false;
});
The scripts should be in List UI. Not in partial views (New, Update, Delete)
//Partial View -
#model User
#Scripts.Render("~/bundles/jqueryval")
#using (Html.BeginForm("Create", "Test1", FormMethod.Post, new { id = "frmNewUser", #class = "form-horizontal" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.UserID)
<p>#Html.ValidationMessage("errorMsg")</p>
...
}
//Do not use Ajax.BeginForm
//Controller -
[HttpPost]
public ActionResult Create(User user)
{
if (ModelState.IsValid)
{
try
{
user.CreatedDate = DateTime.Now;
user.CreatedBy = User.Identity.Name;
string result = new UserRepository().CreateUser(user);
if (result != "")
{
throw new Exception(result);
}
return Content("succes");
}
catch (Exception ex)
{
ModelState.AddModelError("errorMsg", ex.Message);
}
}
else
{
ModelState.AddModelError("errorMsg", "Validation errors");
}
return PartialView("_Create", user);
}
Hope someone get help from this. Thanks all for contributions.
Credit to http://forums.asp.net/t/1649162.aspx
Move the jQuery scripts inside the DIV. This seemed to fix the problem.
The tradeoff is that every post will do a get for each script.
My first post, faced the same issue
here is the solution which worked for me..
#using (Html.BeginForm("", "", FormMethod.Post, new { enctype = "multipart/form-data", id = "MyForm" }))
{
//form fields here..
//don't add a button of type 'submit', just plain 'button'
<button type="button" class="btn btn-warning" id="btnSave" onClick="submitForm()">Save</button>
<script type="text/javascript">
var submitForm = function () {
if ($("#"MyForm").valid())
{
//pass the data annotation validations...
//call the controller action passing the form data..
handleSaveEvent($("#MyForm").serialize());
}
return false;
};
<script>
}

Categories