How do I pass a variable from my View to my Controller? - javascript

I've generated a <select> dropdown menu on my view page with data from a stored procedure. Using JavaScript, I've accessed the selected <option> and saved the text into a variable. Now I need to send that variable back to my controller so I can use it as a parameter in another stored procedure.
Here is my Controller, titled "EventsController.cs"
public ActionResult Dropdown(string text)
{
ViewData["ids"] = db.uspGetAllEventIds().ToArray();
Console.WriteLine(text);
return View();
}
So you can see I run the 1st stored procedure and send it to the view.
Here's what happens in the view:
#model IEnumerable<Heatmap.Models.Event>
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title></title>
<script>
function showValue()
{
var list = document.getElementById("EventId");
var text = list.options[list.selectedIndex].text;
alert(text);
}
</script>
</head>
<body>
<div>
#using (Html.BeginForm("", "", FormMethod.Post))
{
<select id="EventId">
#{
var ids = ViewData["ids"] as string[];
for (var i = 0; i < ids.Length; i++)
{
<option>#ids[i]</option>
}
}
</select>
<input name="text" type="submit" value="Submit" />
<button onclick="showValue()">Click me!</button>
}
</div>
</body>
</html>
So right now I have this alert function just to prove to myself that I have access to the option that I select. I'm pretty sure I need to use FormMethod.Post to get it back to the Controller, but I haven't been able to find any helpful references so far.
How do I format this so my variable text gets sent back into the controller?

I suggest to use jquery $.getJSON method to send and get variable from controller without refresh the page. I added .NetFiddle it works here
[HttpGet]
public JsonResult GetDropdownList()
{
var yourdata = db.uspGetAllEventIds().ToList();
Console.WriteLine(text);
return Json(new { data = yourdata}, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult Dropdown()
{
// add your code here
}
//html
#using (Html.BeginForm("Dropdown","YourControllerName", FormMethod.Post))
{
<select id="EventId" name="eventId">
</select>
<input name="text" type="submit" value="Submit" />
}
<button style="margin-top:20px;" id="yourid">Fill Dropdown!</button>
// jquery
$("#yourid").on("click", function(){
showValue();
})
function showValue()
{
$.getJSON('#Url.Action("GetDropdownList", "YourControllerName")', function (result) {
$("#EventId").html(""); // makes select null before filling process
var data = result.data;
for (var i = 0; i < data.length; i++) {
$("#EventId").append("<option>"+ data[i] +"</option>")
console.log(data[i])
}
})
}

A better way of doing it is you do a postback to your Dropdown(...) action on button click and change its signature to Dropdown(string EventId) which should give you selected EventId.
Here is the full code using both the methods.
public class EventsController : Controller
{
public ActionResult Dropdown()
{
ViewData["ids"] = new[] { 1, 2, 3 };
return View();
}
[HttpPost]
public ActionResult Dropdown(string eventId)
{
//call your sp instead of going back to the same page
ViewData["ids"] = new[] { 1, 2, 3 };
return View();
}
public ActionResult Direct(int id)
{
//call your sp instead of going back to the same page
ViewData["ids"] = new[] { 1, 2, 3 };
return View("Dropdown");
}
}
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title></title>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script>
function showValue() {
var list = document.getElementById("EventId");
var text = list.options[list.selectedIndex].text;
$.getJSON('/Events/Direct/' + text, function(data) {
console.log(data);
});
}
</script>
</head>
<body>
<div>
#using (Html.BeginForm("Dropdown", "Events", FormMethod.Post))
{
<select id="EventId" name="eventId">
#{
var ids = ViewData["ids"] as int[];
for (var i = 0; i < ids.Length; i++)
{
<option>#ids[i]</option>
}
}
</select>
<button type="submit">Postback</button>
}
<button onclick="showValue()">Get JSON</button>
</div>
</body>
</html>

Related

Get selected value from dropdownlist using JQuery and save it in database [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I was able to save dropdownlist value to database before I add the Jquery code:
<select asp-for="CategoriesId" id="CategoriesId" class="form-control" asp-items="ViewBag.CategoriesId">
<option value="0">select</option>
</select>
<script>
$(document).ready(function () {
$("#CarMake").hide();
$('#CategoriesId').on('change', function () {
if (this.value == '2')
{
$("#CarMake").show();
}
else {
//$(this).val()
//$('#CategoriesId').data();
// $('#CategoriesId').val($(this).val());
$('#CategoriesId').text();
}
});
});
I tried all command
Null reference error in this asp.net backend code
ViewData["CategoriesId"] = new SelectList(_context.Categories, "Id", "Titel",ad.CategoriesId);
https://dotnetfiddle.net/nSMhi0
Controller and View Model
public class MyCategory
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
}
public class FatimaViewModel
{
public IList<MyCategory> CategoryList { get; set; }
public int SelectedCategory { get; set; }
}
public class HomeController : Controller
{
[HttpPost]
public ActionResult Index17(FatimaViewModel vm)
{
//put breakpoint here
var selectedItem = vm.SelectedCategory;
FatimaViewModel vmOriginal = PopulateViewModel();
return View(vmOriginal);
}
public ActionResult Index17()
{
FatimaViewModel vm = PopulateViewModel();
return View(vm);
}
View
#model WebApplication2.Controllers.FatimaViewModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous"></script>
<title>Index8</title>
<script>
$(document).ready(function () {
$("#CarMake").hide();
$('#CategoriesId').on('change', function () {
if (this.value == '2') {
$("#CarMake").show();
}
//got rid of unnessary code
});
});
</script>
</head>
<body>
<div>
<div>Select cateogry 2 to show text</div>
<div id="CarMake">This is shown when second category selected</div>
#using (Html.BeginForm())
{
#Html.DropDownListFor(r => r.SelectedCategory, new SelectList(Model.CategoryList, "CategoryId", "CategoryName"), "--select--",
new { id = "CategoriesId" })
<input type="submit" value="Go" />
}
</div>
</body>
</html>

Populate DropDownList from another DropDownList

I have two related models.
public partial class bs_delivery_type
{
public decimal delivery_id { get; set; }
public decimal delivery_city_id { get; set; }
public string delivery_address { get; set; }
public virtual bs_cities bs_cities { get; set; }
}
and the second one:
public partial class bs_cities
{
public bs_cities()
{
this.bs_delivery_type = new HashSet<bs_delivery_type>();
}
public decimal cities_id { get; set; }
public string cities_name { get; set; }
public virtual ICollection<bs_delivery_type> bs_delivery_type { get; set; }
}
and I have such ViewBag's for dropdownlist's:
ViewBag.city = new SelectList(_db.bs_cities, "cities_id", "cities_id");
ViewBag.delivery_adress = new SelectList(_db.bs_cities, "delivery_id", "delivery_address");
When I choose city in first dropdownlist, in the second one there has to be appeared binded list with delivery_adress, where delivery_city_id = cities_id(from first dropdownlist).
How to do that?
Edit:
I tryed method from #Izzy's comment, so here is my actual view:
#model Bike_Store.Models.DeliveryModel
#{
ViewBag.Title = "Checkout";
}
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/jquery-3.1.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript">
function GetDelivery(_stateId) {
var procemessage = "<option value='0'> Please wait...</option>";
$("#ddldelivery").html(procemessage).show();
var url = "/Shop/GetDeliveryByCityId/";
$.ajax({
url: url,
data: { cities_id: _stateId },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select adress</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#ddldelivery").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
</script>
<h2>Checkout</h2>
#using (Html.BeginForm())
{
#Html.DropDownListFor(m=>m.CitiesModel, new SelectList(Model.CitiesModel, "cities_id", "cities_name"), new {#id = "ddldelivery", #style="width:200px", #onchange="javascript:GetDelivery(this.value);"})
<br />
<br />
<select id="ddldelivery" name="ddldelivery" style="width:200px">
</select>
<br /><br />
}
My controller now looks like this:
public List<bs_cities> GetAllCities()
{
List<bs_cities> cities = new List<bs_cities>();
foreach (var city in _db.bs_cities)
{
cities.Add(city);
}
return cities;
}
public List<bs_delivery_type> GetAllDeliveries()
{
List<bs_delivery_type> deliveries = new List<bs_delivery_type>();
foreach (var delivery in _db.bs_delivery_type)
{
deliveries.Add(delivery);
}
return deliveries;
}
[HttpPost]
public ActionResult GetDeliveryByCityId(decimal cities_id)
{
List<bs_delivery_type> delivery = new List<bs_delivery_type>();
delivery = GetAllDeliveries().Where(m => m.delivery_city_id == cities_id).ToList();
SelectList objDelivery = new SelectList(delivery, "delivery_id", "delivery_address", 0);
return Json(objDelivery);
}
public ViewResult Checkout()
{
DeliveryModel deliveryModel = new DeliveryModel();
deliveryModel.CitiesModel = new List<bs_cities>();
deliveryModel.CitiesModel = GetAllCities();
return View(deliveryModel);
}
The problem now is that i have 2 ddls, but works only first one.
In scrshot you can see I have a list of cities, when I choose a city, in this same ddl appears a list of delivery adresses, and when I choose adress - its desappears. What a magic? Help me please with Ajax.
List of cities
I guesse i fixed it, the problem was in:
#Html.DropDownListFor(m=>m.CitiesModel, new SelectList(Model.CitiesModel, "cities_id", "cities_name"), new {#id = "ddldelivery", #style="width:200px", #onchange="javascript:GetDelivery(this.value);"})
I changes #id = "ddldelivery" to #id = "ddlcity" and it works now
The following guide will show you:
Create a partial view
Takes cityid as input and outputs the delivery address list
Load partial view into your select
Note: Partial view solution may be overkill in this situation, but for similar problems it is actually quite usefull.
PartialView .cshtml
Filename: _deliveryTypePartial.cshtml
#model List<bs_delivery_type>
#foreach(var item in Model)
{
<option value="#item.delivery_id">
#item.delivery_address
</option>
}
Controller Code for Partial View:
public IActionResult _deliveryTypePartial(decimal city_id)
{
List<bs_delivery_type> model = context.bs_delivery_types.Where(row => row.delivery_city_id == delivery_city_id).ToList();
return PartialView(model);
}
And then Finally, for your AJAX
I notice that your two dropdownlists have identical ID's witch will cloud your javascript code and is considered bad practice, so for the purposes of this guide I will call the first dropdownlist:
ddlcity
Now, inside your onchange function for ddlcity:
$('#ddldelivery').load("/ControllerName/_deliveryTypePartial?city_id=" _stateId);
This should load the partial view into your second dropdown list.
PS: As I completed this question you had already used the direct ajax method, I agree that both methods are equally suitable in this case. You can perhaps use the method outlined here if the actual objects you need to populate are a lot more complex.

update the multiple partial view using Jquery , MVC and Json not working

I am trying to update the multiple partial view using Jquery , MVC and Json .
My partial views are not updating
Here is my code
My View code is
#model DropdownGrid.Models.MyMultipleUpdateViewModel
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery-1.10.2.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"></script>
<script type="text/javascript">
function _Complete(data) {
var JsonObj = $.parseJSON(data.responseText);
alert(JsonObj);
alert(JsonObj.myTest1ViewModel.MyTestUpdate)
alert(JsonObj.myTest2ViewModel.MyTestUpdate)
$("#Div1").html(JsonObj);
$("#Div2").html(JsonObj);
}
</script>
<br>
<br>
<br>
<br>
<fieldset>
<div id="Div1">
#{ Html.RenderPartial("_MyTest1PartialView", Model); }
</div>
<div id="Div2">
#{ Html.RenderPartial("_MyTest2PartialView", Model); }
</div>
</fieldset>
<fieldset>
#using (Ajax.BeginForm("CreateStudent", "GetStudents",
new AjaxOptions { HttpMethod = "Post", OnComplete = "_Complete" }))
{
<input type="submit" value="Submit" />
}
</fieldset>
My Controller code is
enter code here
public class GetStudentsController : Controller
{
public ActionResult Index()
{
MyMultipleUpdateViewModel obj = new MyMultipleUpdateViewModel();
obj.myTest1ViewModel = new MyTest1ViewModel();
obj.myTest1ViewModel.MyTestUpdate = "Test1";
obj.myTest2ViewModel = new MyTest2ViewModel();
obj.myTest2ViewModel.MyTestUpdate = "Test2";
return View(obj);
}
[HttpPost]
public ActionResult CreateStudent(MyMultipleUpdateViewModel objuserloginmodel)
{
MyMultipleUpdateViewModel obj = new MyMultipleUpdateViewModel();
obj.myTest1ViewModel = new MyTest1ViewModel();
obj.myTest1ViewModel.MyTestUpdate = "Test1"+DateTime.Now.ToString();
obj.myTest2ViewModel = new MyTest2ViewModel();
obj.myTest2ViewModel.MyTestUpdate = "Test2" + DateTime.Now.ToString();
return Json(obj, JsonRequestBehavior.AllowGet);
}
}
And My View model is
public class MyTest1ViewModel
{
public string MyTestUpdate;
}
public class MyTest2ViewModel
{
public string MyTestUpdate;
}
public class MyMultipleUpdateViewModel
{
public MyTest1ViewModel myTest1ViewModel;
public MyTest2ViewModel myTest2ViewModel;
}
It is not working
Could you please help me to resolve my issue.
From your Action method, you are returning a JSON structure like this
{
"myTest1ViewModel": {
"MyTestUpdate": "Test112/12/2015 5:04:57 PM"
},
"myTest2ViewModel": {
"MyTestUpdate": "Test212/12/2015 5:04:57 PM"
}
}
But in your code, you are trying to pass the json object to the html method. you are ideally supposed to pass some html markup to html method.
Since you are having a Json object, you should read the properties of the json object and explicitly set each and every element markup, provided your partial view has items with unique ids.
Assuming your partial view looks like this
#model MyMultipleUpdateViewModel
<div id="testUpdate">#Model.myTest1ViewModel.MyTestUpdate </div>
Inside your javascript method, you can set the markup on the div.
function _Complete(data) {
var JsonObj = $.parseJSON(data.responseText);
$("#testUpdate").html(JsonObj.myTest1ViewModel.MyTestUpdate);
// You may set other properties as well.
}

How to open a message in a modal pop-out when a user successfully/unsuccessfully registers

The code below is the submit button for registering a new user
<div class="col-md-10">
<form method="POST">
<input type="submit" id="" value="Register" class="buttonRegister btn btn-default" style="width: 200px; height: 50px; font-size: 25px"/>
</form>
</div>
This is the Controller for Registering a new user to the database. When a user successfully registers they need to see the ViewBag.ErrorMessage in a modal popout partial view using javascript
I Thought returning the partial view containing the ViewBage.ErrorMessage would be the best idea.
public class RegisterController : Controller
{
// GET: Register
public ActionResult Index()
{
return View("Index");
}
/// <summary>
/// Indexes the specified model.
/// </summary>
/// <param name="model">The model.</param>
/// <returns></returns>
[HttpPost]
public ActionResult Index(PatientScreeningAssignment.Models.Register model)
{
ViewBag.ErrorMessage = null;
ViewBag.ErrorMessage = "Oops something went wrong...";
if (!ModelState.IsValid) return PartialView("~/Views/Shared/_PartialMessage.cshtml");
try
{
//Add new staff to the database
Patient_Screening_Library.Database_Methods.Register.RegisterNewStaff(model.EmailAddress.ToUpper(), model.Password.ToUpper().Trim(),
model.FisrtName.ToUpper(), model.SurName.ToUpper(),
model.JobTitle.ToUpper(),
model.PhoneNumber, model.PagerNumber, model.DateOfBirth
);
//Return Message success
ViewBag.ErrorMessage = null;
ViewBag.ErrorMessage = "Successfully registered user!";
return PartialView("~/Views/Shared/_PartialMessage.cshtml");
}
catch (Exception e)
{
ViewBag.ErrorMessage = null;
ViewBag.ErrorMessage = e.Message;
return PartialView("~/Views/Shared/_PartialMessage.cshtml");
}
}
}
This is in the _PartialMessage View
<!DOCTYPE html>
<head>
</head>
<body>
#ViewBag.ErrorMessage
</body>
I want this to be a popout Modal Form when i click n the submit button which is located in the Register View
Try this
In your partial.
<head>
</head>
<body onload="popupMyMsg('#ViewBag.ErrorMessage')">
</body>
<script>
function popupMyMsg(msg)
{
alert(msg);
}
</script>
Or Redirect in your Register with this
<body onload="popupMyMsg('#ViewBag.ErrorMessage')">
</body>
<script>
function popupMyMsg(msg)
{
if(msg != null && msg!="")
alert(msg);
}
</script>

How to make a delete button permanently delete.

So heres how this works so far,the index page allows you to create a game. Games are then posted onto /data/games ( Gamelist.html). I want to have a button that permanently deletes the games from the list. I currently have a remove button but it doesnt do anything.
Index( create games from here)
<html>
<head>
<title>Planning Poker</title>
<style>
.inlinetext {
display: inline;
}
</style>
<script src="Scripts/jquery-2.1.1.js"></script>
<script src="Scripts/knockout-3.1.0.js"></script>
<script type="text/javascript">
$(function () {
$('#button').on('click', function (data) {
$.post('data/games/create/?title=5', function (d) { console.log(d) });
})
});
</script>
</head>
<body>
<h3 class='inlinetext'> Create Game: </h3>
<input type="text" id="testtext" name="ime">
<button id="button" >Create</button>
</body>
</html>
Controller
using PlanningPoker.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace PlanningPoker.Controllers
{
public class GMController : ApiController
{
private static List<Game> games = new List<Game>() {
new Game() {
ID = Guid.NewGuid(),
Title = "D&D"
}
};
[Route("data/games")]
public IEnumerable<Game> GetAllGames() {
return games;
}
[Route("data/games/create"), HttpPost]
public Guid CreateGame(string title) {
Game g = new Game() {
ID = Guid.NewGuid(),
Title = title
};
games.Add(g);
return g.ID;
}
}
}
Gamelist(html)
<title>Game List</title>
<script src="Scripts/jquery-2.1.1.js"></script>
<script src="Scripts/knockout-3.1.0.js"></script>
<script src="Gamelist.js"></script>
</head>
<body>
<h4>Games</h4>
<ul data-bind="foreach: $data.games">
<li>
Game <span data-bind="text: $index"> </span>:
<span data-bind="text: Title"> </span>
Remove
</li>
</ul>
<button data-bind="click: addGame">Add</button>
</body>
</html>
Gamlist (javascript)
function AppViewModel() {
var self = this;
self.games = ko.observableArray([]);
$.getJSON("/data/games", function (d) {
self.games(d);
});
self.addGame = function () {
self.game.push({ name: "Created On " + new Date() });
};
self.removeGame = function () {
self.game.remove(this);
}
}
$(function () {
ko.applyBindings(new AppViewModel());
});
Knockout will automatically pass back the current item as a parameter in the click event binding...
self.removeGame = function(game) {
self.games.remove(game);
}

Categories