Post HiddenField values to controller with model .net core 6 - asp.net-core-mvc

var tags = M.Chips.getInstance($('.chips')).chipsData;
var sendTags = JSON.stringify(tags, null, 2);
$('#Tags').val(sendTags);
with the above method I stored chips data to hiddenfileds with .onSubmit() method. But at controller level, couldn't get them.
I'am expecting hiddenfiled chips data at contorller level along with other model property.

But at controller level, couldn't get them.
If you want to get the hiddenfileds, I have a suggestion like below:
You can create a hidden input, and use name attribute to bind the data.
<input id="Tags" name="tags" type="hidden" />
The demo like below, you can refer to it:
Privacy view:
<form asp-action="Privacy" method="post">
<input id="Tags" name="tags" type="hidden" />
<input type="submit" value="submit"/>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
var tags = {
'x1': 1,
'x2': 2
}
var sendTags = JSON.stringify(tags, null, 2);
$('#Tags').val(sendTags);
</script>
Controller:
public IActionResult Privacy()
{
return View();
}
[HttpPost]
public IActionResult Privacy( string tags )
{
return View();
}
result:

Related

Passing a predefined Object from View to Controller by form in MVC6

Code in my controller:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult CreateRedBlood(Donor donor)
{
if (ModelState.IsValid)
{
//create
Blood newBlood = new Blood();
if(donor != null)
{
DateTime todaysdate = DateTime.Now;
newBlood = new Blood("RBC", donor.ID);
}
_context.Blood.Add(newBlood);
_context.SaveChanges();
Code in my View:
<form asp-action="CreateRedBlood" method="post">
<div class="form-horizontal">
<h4>Make Donation</h4>
<hr />
<div class="form-group">
<input type="submit" value="Make Red Blood Cell Donation"class="btn btn-default" />
</div>
</div>
</form>
Prior to the use of this form the page has got FullDonorDetails from the controller, and uses model.donor.x to get all the useful bits of information out.
What I'd like to do is pass model.donor back into this form, so that when the button is pressed it takes all that handy information and puts it straight back into CreateRedBlood.
Any ideas?
Thanks!
EDIT: Shyju asked for the following. This is the index controller I'm working with to get fullDonorDetails.
public IActionResult Index(string searchString)
{
FullDonorDetails fullDonorDetails = new FullDonorDetails();
//Get Donor
Donor emptyDonor = new Donor();
Donor activeDonor = new Donor();
if (!string.IsNullOrEmpty(searchString)
&& searchString.Length == 10)
{
activeDonor = _context.Donor.Single(m => m.NHN == searchString);
if (activeDonor != null)
{
fullDonorDetails.Donor = activeDonor;
}
else
{
fullDonorDetails.Donor = emptyDonor;
}
}
else
{
fullDonorDetails.Donor = emptyDonor;
}
//Get History
List<Blood> donorBloodHistory = new List<Blood>();
if (activeDonor != emptyDonor)
{
//RedBlood
var BloodHistory = from r in _context.Blood
select r;
BloodHistory = BloodHistory.Where(s => s.DonorId.Equals(activeDonor.ID));
foreach (Blood currentBlood in BloodHistory)
{
donorBloodHistory.Add(currentBlood);
}
List<Blood> sortedList = donorBloodHistory.OrderBy(o => o.DateTaken).ToList();
sortedList.Reverse();
fullDonorDetails.DonorHistory = sortedList;
}
return View(fullDonorDetails);
}
Since your HttpPost action method is reading only the ID property of the Donor class, which is a parameter of your HttpPost action method, you should keep that property value in a form field with the same name (ID).
#model FullDonorDetails
<form asp-action="CreateRedBlood">
<div class="form-horizontal">
<h4>Make Donation</h4>
<hr />
<input type="hidden" asp-for="Donor.ID" name="ID" />
<div class="form-group">
<input type="submit" value="Make RBC Donation"class="btn btn-default" />
</div>
</div>
</form>
Now when user submits the form, The param of your HttpPost action method will have the value of the Donor ID (which you set in your GET action).

How to use hidden field values from view to controller in asp.net mvc 3

I have to pass hidden filed values to controller action. So I have tried in the following way, but I am getting null values.
I have tried both methods i.e formcollection and viewmodel concept
Controller
public ActionResult MapIcon()
{
Hidden hd = new Hidden();
return View(hd);
}
[HttpPost]
public ActionResult MapIcon(Hidden hidden)
{
var value=hidden.hiddevalue;//null
FormCollection col = new FormCollection();
var value = col["hidden1"];
// string value = mycontroler.ControlName;
return View(hidden);
}
View
#model SVGImageUpload.Models.Hidden
Razor view:#using (Html.BeginForm(new { id = "postform" }))
{
<input type="hidden" id="" value="7" name="hidden1" />
<input type="hidden" id="" value="7" name="hidden2"/>
<input type="submit" value="Match"/>
}
Viewmodel
public class Hidden
{
public string hiddevalue { get; set; }
}
Try this, In Razor view:
#using (Html.BeginForm(new { id = "postform" }))
{
#Html.HiddenFor(m=>m.hiddevalue)
<input type="submit" value="Match"/>
}
It seems to me like you are trying to get multiple values into the POST controller. In that case, and by your exam, the value from the hidden input is enough. In that case, you can setup your controller as so:
public ActionResult Index()
{
Hidden hd = new Hidden();
return View(hd);
}
[HttpPost]
public ActionResult Index(IEnumerable<string> hiddens)
{
foreach (var item in hiddens)
{
//do whatter with item
}
return View(new Hidden());
}
and as for your view, simple change it in order to bind to the same name "hiddens" as so:
#using (Html.BeginForm(new { id = "postform" }))
{
<input type="hidden" value="7" name="hiddens" />
<input type="hidden" value="2" name="hiddens" />
<input type="submit" value="Match" />
}
Hope this serves what you are looking forward to.
if your hidden value is static.Than try this
View
#using (Html.BeginForm(new { id = "postform" }))
{
#Html.HiddenFor(m=>m.hiddevalue)
<input type="hidden" id="" value="7" name="hidden1" />
<input type="hidden" id="" value="7" name="hidden2"/>
<input type="submit" value="Match"/>
}
Controller
[HttpPost]
public ActionResult MapIcon(Hidden hidden, string hidden1, string hidden2)
{
var hiddenvalue = hidden.hiddevalue;
var hiddenvalue1 = hidden1;
var hiddenvalue2 = hidden2;
var value=hidden.hiddevalue;//null
FormCollection col = new FormCollection();
var value = col["hidden1"];
// string value = mycontroler.ControlName;
return View(hidden);
}
Script
$(document).ready(function () {
$('#hiddevalue').val("Jaimin");
});

pass a value of the form from view to controller

how do i pass the value of the form, which is (i assume) a string of date to the controller...
here is my view:
<script type="text/javascript" language="javascript">
$(function () {
$(".datepicker").datepicker({ onSelect: function (dateText, inst) { $("FORM").submit(); },
altField: ".alternate"
});
});
</script>
#model IEnumerable<CorReservation.Models.Reservation>
#{
ViewBag.Title = "Index";
}
<div class="divRightSide">
<div>
<div class="datepicker">
</div>
<form action="/" title="fff">
<input type="text" class="alternate" readonly="readonly" />
</form>
</div>
// do something eg. foreach (var item in Model)
{ #Html.DisplayFor(modelItem => item.Date)}
here is my controller: i want to pass the date selected from the datepicker to the controller and then the controller would return an Ienumerable of reservations...
DateTime date = System.DateTime.Now;
private ReservationEntities db = new ReservationEntities();
public ViewResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string dateInput)
{
date = Convert.ToDateTime(dateInput);
var reservations = db.Reservations.Where(r=> r.Date ==date).Include(r => r.Employee).Include(r => r.Room).OrderByDescending(r => r.Date);
return View(reservations);
}
There are 2 ways to do this. Make the form input name attribute match the expected attribute in your controller.
For example:
<input type="text" class="alternate" readonly="readonly" name="dateInput" />
Or if there's going to be a lot of input values, use a Model.
It's automatically done based on the 'name' attribute of the HTML fields you want to submit.
Change your form to
<form action="/" title="fff">
<input name="dateInput" type="text" class="alternate" readonly="readonly" />
</form>
And it should work just like that.
Also, as you are using Razor syntax, you could use the Razor HTML helpers like so
#model IEnumerable<CorReservation.Models.Reservation>
#{
ViewBag.Title = "Index";
}
<div class="divRightSide">
<div>
<div class="datepicker">
</div>
#using(#Html.BeginForm("<your controller name>", "<your action name e.g. Index>"){
Html.TextBox("dateInput", "", new { #readonly="readonly", #class="alternate" })
}
</div>
// do something eg. foreach (var item in Model)
{ #Html.DisplayFor(modelItem => item.Date)}

Bind Checkboxes to int array/enumerable in MVC

#Html.CheckBox("orderNumbers", new { value = 1 })
#Html.CheckBox("orderNumbers", new { value = 2 })
#Html.CheckBox("orderNumbers", new { value = 3 })
#Html.CheckBox("orderNumbers", new { value = 4 })
#Html.CheckBox("orderNumbers", new { value = 5 })
[HttpPost]
public ActionResult MarkAsCompleted(IEnumerable<int> orderNumbers) { }
[HttpPost]
public ActionResult MarkAsCompleted(IEnumerable<string> orderNumbers) { }
If I use the first signature in my action method, I get an empty IEnumerable.
If I use the second signature I do receive the values but I also receive a false value for the unselected values (because of MVCs pattern of shadowing all checkboxes with a hidden field).
e.g. I will receive something like orderNumbers = { "1", "2", "false", "4", "false" }
Why can't I just get the list of numbers?
You can get all the checked values by the following way.
Controller code :
public ActionResult Index()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(string[] orderNumbers)
{
return View();
}
View Code :
#using (Html.BeginForm())
{
<input name="orderNumbers" type="checkbox" value="1" />
<input name="orderNumbers" type="checkbox" value="2" />
<input name="orderNumbers" type="checkbox" value="3" />
<input name="orderNumbers" type="checkbox" value="4" />
<input name="orderNumbers" type="checkbox" value="5" />
<input type="submit" name="temp" value="hi" />
}
Please keep one thing in my mind that, you need to give same name to all checkboxes. In array you will get values for all checked checkboxes.
Because thats how the provided CheckBoxFor helper is working.
You have to generate the html for the checkboxes yourself. Then the hidden inputs are not generated and you will get only the selected integer values.
In addition to alok_dida's great answer. Since all the values are integers, you can have your controller code take an array of integers and avoid doing the conversion yourself.
This works in MVC4+:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(int[] orderNumbers)
{
return View();
}

Passing input value to action (ASP.Net MVC 3)

I have code in View:
#using (Html.BeginForm("MyAction", "MyController")
{
<input type="text" id="txt" />
<input type="image" src="/button_save.gif" alt="" />
}
How can I pass value of txt to my controller:
[HttpPost]
public ActionResult MyAction(string text)
{
//TODO something with text and return value...
}
Give your input a name and make sure it matches the action's parameter.
<input type="text" id="txt" name="txt" />
[HttpPost]
public ActionResult MyAction(string txt)
Add an input button inside of your form so you can submit it
<input type=submit />
In your controller you have three basic ways of getting this data
1. Get it as a parameter with the same name of your control
public ActionResult Index(string text)
{
}
OR
public ActionResult Index(FormsCollection collection)
{
//name your inputs something other than text of course : )
var value = collection["text"]
}
OR
public ActionResult Index(SomeModel model)
{
var yourTextVar = model.FormValue; //assuming your textbox was inappropriately named FormValue
}
I modified Microsoft MVC study "Movie" app by adding this code:
#*Index.cshtml*#
#using (Html.BeginForm("AddSingleMovie", "Movies"))
{
<br />
<span>please input name of the movie for quick adding: </span>
<input type="text" id="txt" name="Title" />
<input type="submit" />
}
//MoviesController.cs
[HttpPost]
public ActionResult AddSingleMovie(string Title)
{
var movie = new Movie();
movie.Title = Title;
movie.ReleaseDate = DateTime.Today;
movie.Genre = "unknown";
movie.Price = 3;
movie.Rating = "PG";
if (ModelState.IsValid)
{
db.Movies.Add(movie);
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
return RedirectToAction("Index");
}
}

Resources