I have 2 text box and one submit button and one grid in my app. Now i what to add the textbox values to grid while i click the submit button. How to do that?
`
[HttpPost]
public ActionResult AddToCart(string ItemID, string ItemName, CartToCart cart)
{
ViewBag.Message = "This is a partial view.";
List<Models.CartToCart> lst = new List<Models.CartToCart>();
CartToCart ct = new CartToCart();
cart.ItemID = Convert.ToInt32(ItemID);
cart.ItemName = ItemName;
lst.Add(cart);
return View(lst);
}`
View
<% using (Html.BeginForm())
{ %>
<%: Html.ValidationSummary(true)%>
<input id="ItemID" name="ItemID" type="text" />
<input id="ItemName" name="ItemName" type="text" />
<input type="submit" value="Save" />
<%= Html.Telerik().Grid(Model)
.Name("Cart")%>
<% } %>
But while i adding 2nd value 1st value replaced by 2nd value. How to append the 2nd value in grid?
Where do you store the values? Currently you're creating a new empty list on each POST and adding a single value to that list:
List<Models.CartToCart> lst = new List<Models.CartToCart>();
CartToCart ct = new CartToCart();
cart.ItemID = Convert.ToInt32(ItemID);
cart.ItemName = ItemName;
lst.Add(cart);
return View(lst);
So you only ever populate the view with the most recent value, throwing away any previous values. If you want to keep more than just the currently-POSTed value then you'll need to persist them somewhere more permanent, such as a database. So in your controller action you would insert the new POSTed value into the database. Then you'd fetch all of the records from the database as your list of values and return that list to the view.
Related
I try to pass some hidden data to my controller by using the hiddenFor, I know the value I want gets to the view, but after submiting the form the value stays null when it arrives in the controller. The data in EditorFor is passed correctly to the controller.
// View
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
// Some working editorFor fields. Data from these gets successfully received
// The name is correctly displayed in the paragraph
<p>#Model.name</p>
// This data is not received in the controller
#Html.HiddenFor(x => x.name)
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
}
// Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Product product, HttpPostedFileBase image)
{
product.name = "a name";
return View(product);
}
I also tried using a normal named hidden, but this also didn't return a value.
Someone an idea what I missed?
You can pass the hidden fields automatically, if you have a form, using for example the razor helper
#using (Html.BeginForm("CreateTable", "Home", FormMethod.Post, null){ #HiddenFor(i => i.PropertyName) }
and the hidden fields must be inside of form, otherwise you will "lost" them.
Update following your updated question: Try remove the HiddenField and change <p>#Model.name</p>
to
#Html.LabelFor(i => i.Name)
I did focus on the incorrect thing, the problem was that I changed the model in the controller after the postback. But this only changes the model en does not changes the ModelState, which the form data uses.
//This is updated after model changes.
<p>#Model.name</p>
//For this you need to update the ModelState
#Html.HiddenFor(x => x.name)
In the controller you need to use ModelState.Remove(property name). (Or clear the complete ModelState)
//After removal of the property the ModelState will update to the new model value.
product.name = "a name";
ModelState.Remove("name");
return View(product);
In this article it's explained, https://weblog.west-wind.com/posts/2012/Apr/20/ASPNET-MVC-Postbacks-and-HtmlHelper-Controls-ignoring-Model-Changes.
I want the form to pass the values from the hidden inputs to the server and I also expected it to build the URL as
"localhost:9392/Ranking/Index/2?rankingType=SOMEVALUE&ageGroup=SOMEVALUE&week=SOMEVALUE"
but it shows like "localhost:9392/Ranking/Index/2?rankingType=rankingTypeID&ageGroup=ageGroupID&week=week"
#using (Html.BeginForm("Index", "Ranking", new { id = Model.CurrentRanking, rankingType = "rankingTypeID", ageGroup = "ageGroupID", week = "week"}, FormMethod.Post, new { id = "ageGroupForm" }))
{
<input id="ageGroupID" name="ageGroup" hidden />
<input id="rankingTypeID" name="rankingType" hidden />
<input id="week" name="week" hidden />
}
Why is that ? How do I pass the values and also have them show up as query string ?
Try this code:
#using (Html.BeginForm("Index", "Ranking"))
{
<input id="ageGroupID" name="ageGroup" hidden />
<input id="rankingTypeID" name="rankingType" hidden />
<input id="week" name="week" hidden />
}
and in your action method, decorate it like:
public ActionResult Index(string ageGroupID, string rankingTypeID, string week){}
but it shows like "localhost:9392/Ranking/Index/2?rankingType=rankingTypeID&ageGroup=ageGroupID&week=week"
That's because those are exactly the string values you're using:
new { id = Model.CurrentRanking, rankingType = "rankingTypeID", ageGroup = "ageGroupID", week = "week"}
It's not really clear why you're trying to set query string values for the exact form inputs you already have:
<input id="ageGroupID" name="ageGroup" hidden />
<input id="rankingTypeID" name="rankingType" hidden />
<input id="week" name="week" hidden />
If what you're trying to accomplish is to have those values be on the query string (as a GET request) instead of in the request body (as a POST request) then all you have to do is change your form method to a GET:
#using (Html.BeginForm("Index", "Ranking", new { id = Model.CurrentRanking }, FormMethod.Get, new { id = "ageGroupForm" }))
HTML form inputs are automatically added to the request, that's how forms work. You don't need to try to do it manually.
Though it's strange that you're doing this at all. Your inputs are hidden, which usually means you don't want to concern the user with them. But you're also showing them on the URL, which may be confusing to the user (or may even be suspicious to the user). You also aren't setting any values to those hidden inputs, unless you have something else not included here which does that?
Either way, your form will automatically include its inputs in the submitted request.
I have a webgrid contains a dropdown which contains different items for each user(Items are grouped). I want to get the selected values to the controller . How can I do that. Heres my ;
Model :
public SelectList AvailableDevices { get; set; }
View :
...
var grid = new WebGrid(Model. ...
..
..
grid.Column(header: "AvailableDevices", format: #item => Html.DropDownList("value", (IEnumerable<SelectListItem>)item.AvailableDevices)),
And I have a Submit Button
#using (Html.BeginForm("AssignUserDevices", "Device"))
{
<input type="submit" value="setUserDevice" onchange="CheckSelectedDevices()" />
}
I want to set users device according to his user type. I know what his choices and send dropdown items according to his type. So each item in webgrid differs from each other.
And Also I dont know how to give indices to each item in webgrid.( I think we will need it.)
Im new at MVC so hope you will understand.
Thanks;
What I got from our requirement that you want the selected item and have that item value in form field before posting if yes then you can follow as given.
#Html.DropDownList("value", (IEnumerable<selectlistitem>)item.AvailableDevices), new {#class="deviceclass"} )
#using (Html.BeginForm("AssignUserDevices", "Device"))
{
<input type="hidden" value="" name="deviceId" id="deviceId" />
<input type="hidden" value="" name="userId" />
<input type="submit" value="setUserDevice" />
}
<script>
$(".deviceclass").on('change', function () {
var dropdownvalue = $(this).val();
$('#deviceId').val(dropdownvalue);
})
</script>
and you can define an action function in controller
public ActionResult Details(string deviceId, string userId)
{
// do as you need.
return View();
}
I want to display the price of the selected item in the textbox in the view. For example, a product selected from the DLL has a price of 10 € and it should be displayed in the view. Can someone help?
Controler
public ActionResult Edit(int id)
{
Product product = DB.Products.Find(id);
ViewBag.Formats = new SelectList(storeDB.Format, "FormatID", "FormatName", "Price");
ViewBag.Foo = "Some Value"; //test
return View(product);
}
View
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<div class="editor-field">
#Html.DropDownList("Formats", ViewBag.Formats as SelectList, new { id = "DDLFormatsID" })
#Html.Display("Price") //displays nothing
#Html.Display("Foo") //working properly
</div>
</fieldset>
}
Update:
The problem seems to be in the order of the parameters in the constructor of the SelectList. I changed this line and it worked as you expected, showing the prices.
ViewBag.Formats = new SelectList(storeDB.Format, "FormatID", "Price");
You can check for the use of each parameter in the constructor. The first is for the data, the second is the name of the property that will hold the data to be send on the post, the third is the name of the property to be displayed.
Answer to the updated question:
If you want to show some value depending on the value in the dropdown then you can do it using javascript. First You have to identify the control to put your value, I'll use a span but you can use a textbox, etc. Then you subscribe to the change event of the dropdown and change the content of the first control every time.
Note that I'm using the value of the select to store the prices. If you want to receive the value as the id of the item you cannot use this approach. You need to store the prices in another place, you can use hidden elements.
You have to reference the jQuery library in the view.
The code is this:
public ActionResult Edit(int id)
{
Product product = DB.Products.Find(id);
ViewBag.Formats = new SelectList(storeDB.Format, "Price", "FormatName");
return View(product);
}
View
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<div class="editor-field">
#Html.DropDownList("Formats", ViewBag.Formats as SelectList, new { id = "DDLFormatsID" })
<span id="priceHolder"></span>
</div>
</fieldset>
}
<script src="~/Scripts/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#Formats").change(function () {
var $this = $(this);
var selectedValue = $this.val();
$('#priceHolder').html(selectedValue);
});
});
</script>
So in my view I am dynamically creating dropdown lists in a for loop. I use the same name value in unique id values.
#foreach(var item in Model.Items)
{
#Html.DropDownList("Items" Model.GenerateSelectList(item.id), new { id = item.id })
}
In my controller action method for the post I can get the values of the dropdowns like this:
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize]
public ActionResult ClassicLineup(IList<int> items)
{
}
I cannot figure out how to get BOTH the dropdown id and associated value.
Seems like it should be simple but it has me stumped...
Thanks.
On form submit browser sends only the selected value of a dropdown, so there is no bult in mechanism to read the text of selected item, but you can create one for you.
In below code i have created a hidden input which stores the text of current selected item, and is send to the server on form post.
You can create below list in controller or in view (preferred place in controller);
var items= (from item in Model.Items
select new SelectListItem
{
Value= item.DisplayProperty
Text= item.Value
}).toList();
<form action="controller/test">
#*This will create DD*#
#Html.DropDownList("MyDropDownList", items)
#*Hidden input*#
<input type="hidden" id="ddSelectedName" name="ddSelectedName" />
<br>
<input type="submit" value="submit"/>
</form>
Include jQuery in ur code and then add this
<script type="text/javascript">
$('#MyDropDownList').change(function () {
$('#ddSelectedName').val($(this).find(':selected').text());
});
</script>
Controller
public string test(string MyDropDownList, string ddSelectedName)
{
return MyDropDownList+ "--"+ddSelectedName ;
}
I just ended up looping through the forms collection and parsing the dropdown id (form.key) and the dropdown value (form.key.value).
Apparently there is not an easy way to have MVC bind the dropdown values and id to a collection in the controller action parameter.