Confirm Box not stopping controller action - javascript

Giving the user the option to see the rows returned from the search or not. If I hit Cancel, it still runs the controller code.
HTML:
<td><input type="submit" name="SubmitSearch" id="search" value="Search" class="form-control alert-success" onclick="return rowcount()" /></td>
Javascript:
<script type="text/javascript">
function rowcount() {
confirm("There are rows");
}
Controller:
[HttpPost]
public ActionResult OracleVerification(string company, string location, string product, string department)
{
List<OracleStringViewModel> oracleStringList = OracleStringRepository.GetOracleStrings(company, location, product, department);
return View(oracleStringList.ToList());
}

The construct confirm() returns true or false. You need to make use of it. You forgot to use the return keyword:
function rowcount() {
return confirm("There are rows");
}
The problem here is, the confirm actually returns the boolean value from the user, but it goes nowhere. You need to return it back to the calling place, which is the input's onclick event.

Related

MVC Ajax.BeginForm JavaScript parameters

I have an AJAX form where the url id needs to be from JavaScript
#using(Ajax.BeginForm("Add","Comments", new { ArticleID = 3 }, new AjaxOptions { UpdateTargetId="Comments"}))
Where ArticleID = 3 should be replaced so that the ArticleID value is set equal to the result of a called Javascript function. Something like
JS:
function GetArticleID()
{
return 3;
}
Razor:
#using(Ajax.BeginForm("Add","Comments", new { ArticleID = GetArticleID() }, new AjaxOptions { UpdateTargetId="Comments"}))
Controller:
public ActionResult Add(int ArticleID, Comment model)
{
}
How can I use JavaScript function result as BeginForm parameter?
The line #using(Ajax.BeginForm(" will be executed by razor on server. At that time it does not have any knowledge of the javascript methods in your client browser. So you cannot mix a javascript function there.
I prefer to write clean custom code to do the ajax form submit (instead of using Ajax.BeginForm) because it allows me to customize any way i want.
Keep your form as a normal form.
#using(Html.BeginForm("Add","Comments"))
{
<input type="hidden" name="ArticleId" id="ArticleId" value=""/>
<input name="CommentText" type="text" />
<input type="submit" id="saveCmntBtn" />
}
Now listen to the click event of the submit button. Assign the ArticleId value to the input field, get the serialized version of the form and post to server. You may use jQuery serialize() method to get the serialized version of your form.
$(function(){
$("#saveCmntBtn").click(function(e){
e.preventDefault();
$("#ArticleId").val(GetArticleID());
var f=$(this).closest("form");
$.post(f.attr("action"),f.serialize(),function(res){
$("#Comments").append(res);
});
});
});

Passing additional value to Controller method - Razor/MVC 5

Hello I am having some trouble figuring out how to pass an additional value to my Controller's Delete method.
I have a form with a Delete button (auto-generated MVC).
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-actions no-color">
<input type="submit" value="Delete" class="btn btn-sm btn-danger" />
<button onclick="location.href='#Url.Action("Index", "Admin")';return false;" class="btn btn-sm btn-primary" style="font-size:10px">Admin</button>
</div>
}
But I want to send along an additional value, this value would be the result of getCookie("username");
I have tried making another input and calling it.
<input type="text" name="userid" value="getCookie('username')" />
The problem is that this always shows "null" within my Controller method.
The method is
// GET: /Admin/Delete/5
public ActionResult Delete(int? id, string userid)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
User user = db.Users.Find(id);
if (user == null)
{
return HttpNotFound();
}
return View(user);
}
and
// POST: /Admin/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id, string userid)
{
User user = db.Users.Find(id);
db.Users.Remove(user);
db.SaveChanges();
var time = new DateTime();
string text = time + ": User " + user.name + " was deleted.";
System.IO.File.AppendAllText(pathway, text + Environment.NewLine);
return RedirectToAction("Index");
}
All I want is to have the value of getCookie('username'); passed on to a method as userID.
Any help appreciated!
What you would want to do is have getcookie() set the value (using jQuery, or whatever) of the userId instead of returning it. You'd need to call this on page load. That would put the value in the DOM/form, so it posts to your controller action.
That said, can't you just access the cookies in your action from the Request object?

requesting a server by checking/unchecking checkboxes

I'm trying to code a web page that contains two checkboxes and to send a request to my web server for each check/uncheck. I have to check at server side which checkboxes are checked and which are not to make some specific operations.
Form (snippet of code) :
<form method="get" action="#Url.Action("Index")" data-monitoring-ajax="true" data-monitoring-target="#ListeAlertes">
<input type="checkbox" name="affiche" value="fixees" id="fixees" style="margin-left:40px;margin-right:3px;" checked /> Alertes fixées
<input type="checkbox" name="affiche" value="nonFixees" id="nonFixees" style="margin-left:10px;margin-right:3px;" checked /> Alertes non-fixées
</form>
monitoring.js
$(function () {
var ajaxFormSubmit = function () {
var $form = $(this);
var options = {
url: $form.attr("action"),
type: $form.attr("method"),
data: $form.serialize()
};
$.ajax(options).done(function (data) {
var $target = $($form.attr("data-monitoring-target"));
$target.replaceWith(data);
});
return false;
}
$("form[data-monitoring-ajax='true']").submit(ajaxFormSubmit);
});
Note : I've included monitoring.js into the web page.
Any brilliant idea, please ?
Since the options seem to represent the same item just in a different state, you really only need one checkbox.
The Html
<input type="checkbox" id="enableAlerts" style="margin-left:40px;margin-right:3px;" /> Alertes fixées
The javascript (jQuery)
With this, you can subscribe to the change event to know when to send the request to the server.
$("#enableAlerts").change(function(){
$.post("/Controller/UpdateAlerts",
{ enableAlerts: this.checked },
function(data){ console.log("Successfully saved user options!"); });
});
In the above script we listen for the change event to fire and when it does, we post our data to the server so it can process it. If the server returns a 200 status code, it will write to the console that it was successful. Since only one checkbox is being sent, there isn't any reason to wrap the checkbox in a form and serialize the form to send to the server.
The Server code
Now all you need is a controller/action to call to update the option on the server.
[HttpPost]
public HttpStatusCodeResult UpdateAlerts(bool enableAlerts)
{
//Save to database
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
The above code allows the javascript code to post the data to the server. In this case I allowed the value to be nullable and default to false if so. After that, do what you need to and return a response code so the client-side code can inform the user of the status of their request.
In response to comment by user
In this case wrapping it in a form would be correct. The majority of the steps are similar with minor modifications.
Html
<form method="post" id="filterOptions">
<input type="checkbox" name="Checkbox1" value="true" />
<input type="checkbox" name="Checkbox2" value="true" />
</form>
Javascript
$("#filterOptions input[type='checkbox']").change(function () {
var form = $("#filterOptions").serialize();
$.post("/Controller/AjaxFilteredList",
form,
function (data) { console.log("Retrieved data successfully!") });
});
The Model
public class MyModel
{
public bool Checkbox1 { get; set; }
public bool Checkbox2 { get; set; }
}
The model's property names must match the name of the property, case-insensitive. This is made easier if you make this a ViewModel and pass it into the repective View and use Html.CheckboxFor(m => m.Checkbox1) to render the checkbox.
The controller action
[HttpPost]
public ActionResult AjaxFilteredList(MyModel model)
{
//check you viewmodel's variables to get your list
return PartialView("_FilteredList", filteredList);
}
The above assumes you have a partial view named "_FilteredList" and a variable named "filteredList" in-scope with the results you want to render.
Use .change()
$("form[data-monitoring-ajax='true'] input[type='checkbox']").change(function(){
//make your Ajax Call here and send name of the checkbox or id of the checkobox
});
Attribute Equals Selector [name="value"]

ASP.NET MVC Controller Result return to view

I'm working in ASP MVC & C#, and what i'm trying to do is something similar to the following.
public JsonResult SendMessage(SMSTestViewModel model)
{
if (//logic here)
{
string phonenumber = model.phone.ToString();
string derp = string.Empty;
//SMS.SendSMS(phonenumber, "testing heheheheh", derp);
var result = new { Success = "True", Message = "Good Job" };
return Json(result, JsonRequestBehavior.AllowGet);
}
var result = new { Success = "False", Message = "Didn't work" };
return Json(result, JsonRequestBehavior.AllowGet);
}
That's the code block in my controller, and now I'm trying to reference this in my View with the following
<p>Please enter your phone number</p>
<table>
<tr>
<td>Phone Number</td>
<td> <input id = "phone" type ="text" name= "phone" /></td>
</tr>
</table>
<input type="button" value="Submit" id="sendMSG">
<script>
$('sendMSG').click(function(){
$.getJSON('SMSTestController/SendMessage', function (data) {
alert(data.Success);
alert(data.Message);
});
});
</script>
For some reason the alerts wont show up. And It's quite confusing to me.
I'm really new to JSON, JQuery and Javascript so any help or recommendations would be greatly appreciated.
Thanks
EDIT:
Changed the html code block to the following:
<input type="button" value="Submit" id="sendMSG">
<script>
$('#sendMSG').click(function () {
$.getJSON('#Url.Action("SendMessage","SMSTestController")', function (data) {
alert(data.Success);
alert("test");
alert(data.Message);
});
});
</script>
Most likely, the URL in your $.getJSON call is incorrect. You have it relative to whatever URL you're currently looking at.
Try changing that line to be:
$.getJSON('#Url.Action("SendMessage", "SMSTestController")', function (data) {
This way, MVC generates an absolute URL to your action.
Edit:
Your jQuery selector of your button is wrong.
$('sendMSG')
Since you're searching for it by id, use:
$('#sendMSG')
Changing the url to the following should make it work
'/SMSTestController/SendMessage'
However, the better solution is as Matt had mentioned
'#Url.Action("SendMessage", "SMSTestController")'
Also, Have a look at this Fiddle http://jsfiddle.net/Ukuyc/

Validation on a JS function

I have a list of people that are being added via a search. Everything works, but there's one case where if you don't select a person from this list, you get an ugly 400 page. Obviously it's because I'm not handling the validation there.
My "remove from list" button is done this way:
<input type="button" value="Remove" onclick="delTeamNominee(document.f.teamList.value)"/>
Here's my function:
function delTeamNominee(id) {
document.dl.empId.value = id;
document.dl.submit();
}
dl is a hidden form that executes a Spring MVC method:
<form name="dl" action="teamDeleteEmployee" method="post">
<input type="hidden" name="empId">
</form>
Obviously I would like to do something like this:
function delTeamNominee(id) {
if (id == null) {
alert("You must select a person");
} else {
document.dl.empId.value = id;
document.dl.submit();
}
}
Which of course, doesn't work.
Perhaps you should also check to see if id is undefined. Something like the following will catch both null and undefined:
if (!id) {
....
}

Categories

Resources