Viewbag is null in alert - asp.net-mvc

i wrote behind code.
but Viewbag.message will show null in alert message .myvar is a variable.
i used breakpoint , myvar will set by Viewbag.message correctly. but it will be shown null in alert .
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
#{string myvar = ViewBag.AlertMessage;}
#using (Ajax.BeginForm("action", "controller", new AjaxOptions { HttpMethod = "Post", OnSuccess = "Messsage" }))
{
<script type="text/javascript">
function Messsage() {
alert('#ViewBag.AlertMessage'); //infact, it shows alert('');
}
</script>

<script type="text/javascript">
function Messsage() {
alert('#myvar'); // should show "hello there"
}
</script>
#using (Ajax.BeginForm("AjaxAction", "Home", new AjaxOptions { HttpMethod = "Post", OnSuccess = "Messsage" }))
{
<script type="text/javascript">
function Messsage() {
alert("#ViewBag.AjaxMessage");
}
</script>
<input type="submit" value="Submit" />
}

is the ViewBag.AlertMessage being defined in the controller action ?
you can replace the data by
#{string myvar = "hello there !";}
<script type="text/javascript">
function Messsage() {
alert('#myvar'); // should show "hello there"
}
</script>
or define your viewbag item in the action method behind the result
public ActionResult Index() {
ViewBag.AlertMessage = "hello there !"
return View();
}

Try setting the value for ViewBag.AlertMessage in controller action that returns the view on which you have defined the Ajax.Begin form.
eg
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
ViewBag.AlertMessage = "AjaxMessage.";
return View();
}
}
on Index view i have placed the following code, calling AjaxAction on Home Controller.
#using (Ajax.BeginForm("AjaxAction", "Home", new AjaxOptions { HttpMethod = "Post", OnSuccess = "Messsage" }))
{
<script type="text/javascript">
function Messsage() {
alert("#ViewBag.AjaxMessage");
}
</script>
<input type="submit" value="Submit" />
}

Related

Submit button doesn't hit controller due to [ValidateAntiForgeryToken()] And Disabled Cookies

I am using #Html.AntiForgeryToken() , but due to this code , when i click on submit, it doesn't hit action in controller.
#using (Ajax.BeginForm("Action", "COntroller",null, new AjaxOptions { OnBegin = "$('#dvLoading').removeClass('displayNone');", OnSuccess = "ShowResultUpsID(data);", OnFailure = "$('#dvLoading').addClass('displayNone'); Showerror(); scrollToTop();" }, new { #id = "CreateID", #Name = "CreateID" }))
{
#Html.AntiForgeryToken()
}
below is my Action
[HttpPost]
[ValidateAntiForgeryToken()]
public ActionResult MyAction(Model object)
{
}
Note: with cookie disabled.
You need to add jquery.unobtrusive-ajax library to your project.
which help you to work with Html Ajax forms.
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script type="text/javascript">
function OnSuccess(resolve) { console.log(resolve) }
function OnFailure(error) { console.log(error) }
function OnComplete(resolve) { console.log(resolve) }
</script>
#using (Ajax.BeginForm("AddUser", new AjaxOptions { HttpMethod = "POST", OnSuccess = "OnSuccess", OnComplete = "OnComplete", OnFailure = "OnFailure" }))
{
#Html.AntiForgeryToken();
#Html.HiddenFor(x => x.Id)
#Html.TextBoxFor(x => x.FirstName)
#Html.TextBoxFor(x => x.LastName)
<button>Save</button>
}
[HttpPost, ValidateAntiForgeryToken]
public ActionResult AddUser(UserModel model)
{
return Json(model, JsonRequestBehavior.AllowGet);
}

how to get ID from URL in asp.net MVC controller

I want to get the ID from URL in ASP.NET MVC Controller and insert it into Project_ID, the bellow is my code, i tried but its now working for me.
http://localhost:20487/ProjectComponent/Index/1
My Controller
[HttpPost]
public JsonResult SaveComponent(OrderVM O, int id)
{
bool status = false;
if (ModelState.IsValid)
{
using (Entities db = new Entities())
{
ProjComponent ProjComponent = new ProjComponent { project_id = id, title = O.title, description = O.description };
foreach (var i in O.ProjComponentActivities)
{
ProjComponent.ProjComponentActivity.Add(i);
}
db.ProjComponents.Add(ProjComponent);
db.SaveChanges();
status = true;
}
}
}
You can always use a hidden field and update it by jquery/javscript and send it to back end in ajax helper.....
Make sure 1.name should be exactly name as ActionMethod param and 3.Jquery ,jQuery Validate and jQuery unobstrusive ajax is loaded correctly
My code .cshtml
<script src="~/Scripts/jquery-2.1.4.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<div>
#{
AjaxOptions options = new AjaxOptions();
options.HttpMethod = "POST";
options.OnBegin = "OnBeginRequest";
options.OnSuccess = "OnSuccessRequest";
options.OnComplete = "OnCompleteRequest";
options.OnFailure = "OnFailureRequest";
// options.Confirm = "Do you want to Add Country ?";
options.UpdateTargetId = "divResponse";
options.InsertionMode = InsertionMode.InsertAfter;
}
#using (Ajax.BeginForm("AjaxSend", "Stackoverflow", options))
{
<input type="hidden" name="project_id" id="project_id" value="project_id" />
<input type="submit" value="Click me" />
}
</div>
<div id="divResponse">
</div>
<script>
$(function() {
var url = window.location.href;
var array = url.split('/');
var lastsegment = array[array.length - 1];
console.log(lastsegment);
$('#project_id').val(lastsegment);
});
function OnBeginRequest() {
console.log('On Begin');
}
function OnCompleteRequest() {
console.log('On Completed');
}
function OnSuccessRequest() {
console.log('On Success');
}
function OnFailureRequest() {
console.log('On Failure');
}
</script>
and Controller
[HttpPost]
public JsonResult AjaxSend(String project_id)
{
//rest goes here
return Json(new { Success = true });
}
this link may help link
you can get the id from URL Like This:
Cotroller:
public ActionResult Index(int id)
{
ViewBag.ID = id;
Your Code......
return View(...);
}
View:
#{
ViewBag.Title = "Index";
var ID = ViewBag.ID;
}
Now you have an ID in the variable

Can't pass selected value DropDownListFor to javascript function

My simpel test Model:
public class MovieModel {
public string SelectedCategorieID { get; set; }
public List<CategorieModel> Categories { get; set; }
public MovieModel() {
this.SelectedCategorieID = "0";
this.Categories = new List<CategorieModel>() {new CategorieModel {ID = 1,
Name = "Drama"},
new CategorieModel {ID = 2,
Name = "Scifi"}};
}
}
public class CategorieModel {
public int ID { get; set; }
public string Name { get; set; }
}
My Home controller action Index:
public ActionResult Index() {
Models.MovieModel mm = new Models.MovieModel();
return View(mm);
}
My strongly typed View:
#model MvcDropDownList.Models.MovieModel
#{
ViewBag.Title = "Home Page";
}
<script type="text/javascript">
function categoryChosen(selectedCatID) {
// debugger;
var url = "Home/CategoryChosen?SelectedCategorieID=" + selectedCatID;
$.post(url, function (data) {
$("#minicart").html(data);
});
}
</script>
#using (Html.BeginForm("CategoryChosen", "Home", FormMethod.Get)) {
<fieldset>
Movie Type
#Html.DropDownListFor(m => m.SelectedCategorieID, new SelectList(Model.Categories, "ID", "Name", Model.SelectedCategorieID), "---Select categorie---")
<p>
<input type="submit" value="Submit" />
</p>
</fieldset>
}
<input type="button" value="Minicart test" onclick="categoryChosen('#Model.SelectedCategorieID');" />
<div id="minicart">
#Html.Partial("Information")
</div>
Please ignore the first input, because I'm using the second input with 'Minicart test' on it (the HTML.Beginform is there to learn something else later). The mini cart stuff is from another tutorial, I apologize. Don't let it distract you please.
When the button is clicked categoryChosen jQuery is called, which calls the action:
[AcceptVerbs("POST")]
public ActionResult CategoryChosen(string SelectedCategorieID) {
ViewBag.messageString = SelectedCategorieID;
return PartialView("Information");
}
The partial view Information looks like this:
#{
ViewBag.Title = "Information";
}
<h2>Information</h2>
<h2>You selected: #ViewBag.messageString</h2>
My question is why is Model.SelectCategorieID zero (Model.SelectCategorieID = 0) even after I changed the value in the dropdownlist? What am I doing wrong? Thank you very much in advance for answering. If you need any information or anything in unclear, please let me know.
My question is why is Model.SelectCategorieID zero
(Model.SelectCategorieID = 0) even after I changed the value in the
dropdownlist?
That's because you have hardcoded that value in your onclick handler:
onclick="categoryChosen('#Model.SelectedCategorieID');"
If you want to do that properly you should read the value from the dropdown list:
onclick="categoryChosen(this);"
and then modify your categoryChosen function:
<script type="text/javascript">
function categoryChosen(ddl) {
// debugger;
var url = 'Home/CategoryChosen';
$.post(url, { selectedCategorieID: $(ddl).val() }, function (data) {
$('#minicart').html(data);
});
}
</script>
Also I would recommend you using an URL helper to generate the url to invoke instead of hardcoding it in your javascript function. And last but not least, I would recommend you doing this unobtrusively, so that you could put this in a separate javascript file and stop mixing markup and script.
So here's how your code will look like after taking into consideration my remarks:
#model MvcDropDownList.Models.MovieModel
#{
ViewBag.Title = "Home Page";
}
#using (Html.BeginForm("CategoryChosen", "Home", FormMethod.Get))
{
<fieldset>
Movie Type
#Html.DropDownListFor(
m => m.SelectedCategorieID,
new SelectList(Model.Categories, "ID", "Name"),
"---Select categorie---",
new {
id = "categoryDdl"
data_url = Url.Action("CategoryChoosen", "Home")
}
)
<p>
<input type="submit" value="Submit" />
</p>
</fieldset>
}
<input type="button" value="Minicart test" id="minicart-button" />
<div id="minicart">
#Html.Partial("Information")
</div>
and then in your separate javascript file unobtrusively subscribe to the click handler of your button and send the AJAX request:
$(function() {
$('#minicart-button').click(function() {
// debugger;
var $categoryDdl = $('#categoryDdl');
var selectedCategorieID = $categoryDdl.val();
var url = $categoryDdl.data('url');
$.post(url, { selectedCategorieID: selectedCategorieID }, function (data) {
$('#minicart').html(data);
});
});
});
Provide an id for your dropdownlist:
#Html.DropDownListFor(m => m.SelectedCategorieID, new SelectList(Model.Categories, "ID",
"Name", Model.SelectedCategorieID), new {id = "myDropDownList"})
And your javascript function as follows:
<script type="text/javascript">
function categoryChosen() {
var cat = $("#myDropDownList").val();
var url = "Home/CategoryChosen?SelectedCategorieID=" + cat;
$.post(url, function (data) {
$("#minicart").html(data);
});
}
</script>
Why your code did not work?
onclick="categoryChosen('#Model.SelectedCategorieID')
is generated as
onclick="categoryChosen('0')
because the value of SelectedCategorieID is 0 when it is generated.

ASP.NET MVC 3 AJAX request returns 404 Not Found error

Here's my code (question found below):
VIEW
// This function is called by another function when radioButtonGroup.change().
var requestValues = function (form) {
var option = form.find("input:radio:checked").attr("value");
// This seemingly shows the correct url for the action method desired.
alert("Form Action: " + form[0].action + "\nForm Method: " + form[0].method);
if (form.valid()) {
$.ajax({
url: form[0].action,
type: form[0].method,
data: option,
success: function (result) {
alert("Had success.");
$('#createForm').replaceWith(result);
},
error: function (xhr) {
alert("An error occurred: " + xhr.status + " " + xhr.statusText);
}
});
}
return false;
}
...(other code here)...
#using (Html.BeginForm("CreateForm", "MyController", FormMethod.Post,
new { #id = "optionForm" }))
{
<div id="options">
#foreach (MyOption op in Model.GetOptions()) {
<div class="editor-field">
#Html.RadioButton("formOption", op.OptionType, false,
new { #id = op.ID, #title = #op.Description })
<label for="#op.ID">#op.Name</label>
</div>
}
</div>
<input type="submit" value="Select" style="display:none;" />
}
CONTROLLER
[HttpPost]
public PartialViewResult CreateForm(MyOptionType formOption) {
MyViewModel model = new MyViewModel();
model.ApplyOptionValues(formOption);
return PartialView("_CreateForm", model);
}
REGISTER ROUTES
// Default
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
My issue is that when I click a radio button, the AJAX request executes but I get a "404 Not Found" error (even though the alert in the jQuery function seems to show the appropriate url). I spent all day yesterday on this, and I cannot figure out what the heck is wrong. I'm running ASP.NET MVC 3 app on IIS Express, and I'm not using Areas (that I know of anyway). Anyone have any suggestions on how to fix this? Thanks.
EDIT
The alert box shows the following message:
Form Action: https://localhost:44300/MyController/CreateForm
Form Method: post
EDIT
Here is an entire test view and test controller that recreates the error:
VIEW
<h2>TestAction</h2>
<script type="text/javascript">
$(document).ready(function () {
$("#optionForm input[name='radioOption']").change(function () {
requestValues($(this).closest("form"));
});
var requestValues = function (form) {
var option = form.find("input:radio:checked").attr("value");
alert("Form Action: " + form[0].action + "\nForm Method: " + form[0].method);
if (form.valid()) {
$.ajax({
url: form[0].action,
type: form[0].method,
data: option,
success: function (result) {
alert("AJAX success.");
//$('#createForm').replaceWith(result);
},
error: function (xhr) {
alert("An error occurred: " + xhr.status + " " + xhr.statusText);
}
});
}
return false;
}
});
</script>
#using (Html.BeginForm("CreateForm", "Test", FormMethod.Post, new { #id = "optionForm" })) {
#Html.RadioButton("radioOption", "value1", false, new { #id = "radioButton1" })
<label for="radioButton1">Radio Button 1</label>
#Html.RadioButton("radioOption", "value2", false, new { #id = "radioButton2" })
<label for="radioButton2">Radio Button 2</label>
#Html.RadioButton("radioOption", "value3", false, new { #id = "radioButton3" })
<label for="radioButton3">Radio Button 3</label>
<input type="submit" value="Select" style="display:none;" />
}
<div id="createForm"></div>
CONTROLLER
public class TestController : Controller {
public ActionResult TestAction() {
return View();
}
[HttpPost]
public ActionResult CreateForm(string option) {
return View("TestAction");
}
}
#using (Html.BeginForm("CreateForm", "MyController", FormMethod.Post, new { id = "optionForm" }))
should be:
#using (Html.BeginForm("CreateForm", "My", FormMethod.Post, new { id = "optionForm" }))
Remember that in ASP.NET MVC helpers you should not pass the Controller suffix. It is assumed.
So the correct url should be:
https://localhost:44300/My/CreateForm
and not:
https://localhost:44300/MyController/CreateForm
where you obviously have the MyController class:
public class MyController: Controller
{
public ActionResult CreateForm(MyOptionType formOption)
{
...
}
}

update div in ajax in asp.net mvc

i have written my codes by ajax as following : instead of updating div,has redirected to partial view.
according to update target id of ajax option is set,it cant update.
please help me
public class SearchController : Controller
{
public ActionResult search()
{
return View();
}
public PartialViewResult _search()
{
Thread.Sleep(3000);
ViewBag.message = "test";
return PartialView("_search");
}
}
#{
ViewBag.Title = "search";
}
<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<h2>search</h2>
#Ajax.ActionLink("Click",
"_search",
new AjaxOptions
{
UpdateTargetId = "_search",
InsertionMode = InsertionMode.InsertAfter,
HttpMethod = "GET"
}
)
<div id="_search">
</div>
Make sure you have following scripts added into either of your view or masterview
jquery.unobtrusive-ajax.min.js
MicrosoftAjax.js
MicrosoftMvcAjax.js
try this
#Ajax.ActionLink("Click",
"_search",
null,
new AjaxOptions
{
UpdateTargetId = "_search",
InsertionMode = InsertionMode.InsertAfter,
HttpMethod = "GET"
}
)

Resources