I've got this nice list in my View, and it has many values, so how can I like merge all the values and return it to my Controller?
<ul>
<li>Alex</li>
<li>Bobby</li>
<li>Camilla</li>
<li>Denise</li>
<li>Elise</li>
<li>Francis</li>
</ul>
Edit
My View is like, I have a textbox to enter a name, then I click the "add" button, and it's added in the list by jQuery.
So when the add button is clicked, I'd like to send all names to the Controller
You need to put those itens inside a form on your view
#using (Html.BeginForm())
{
<ul>
<li>Alex<input type="hidden" name="names" value="Alex"></li>
<li>Bobby<input type="hidden" name="names" value="Bobby"></li>
<li>Camilla<input type="hidden" name="names" value="Camilla"></li>
<li>Denise<input type="hidden" name="names" value="Denise"></li>
<li>Elise<input type="hidden" name="names" value="Elise"></li>
<li>Francis<input type="hidden" name="names" value="Francis"></li>
</ul>
<button type="submit">GOO</button>
}
then on your controller
[HttpPost]
public ActionResult Index(List<string> names)
{
return View();
}
Related
I saw many post regarding multiple button calling Action method, But those are all without Input.
I have Razor View. It will generate multiple Inputs and Buttons
Example
Item View
#foreach (var item in ViewBag.Prod)
{
<input type="text" id="txtQuantity" class="form-control txtQty">
<button type="button" data-src="#(item.ItemID)" class="btn btn-primary btn-sm" onclick="location.href='#Url.Action("AddValue", "MyController")'" id="btnAddItem-#(item.ItemID)" style="margin-top: 15px;">Add</button>
}
So above code may generate, 5 textboxes and 5 Add button, every button click will call below action method.
How can I get the respective textbox value. For instance, if user enter value = 16.5 on 5th textbox, and click 5th button, I need to get the value of what user entered on that 5th textbox
ActionResult method
public ActionResult AddValue()
{
//I need to get the entered textbox value
return RedirectToAction("Item");
}
If you only need to capture input for that specific line or row, then you could enclose them with a form tag during the loop.
EDIT: Don't forget to add a Name attribute to your input field. I used Quantity for input and ID for the button. Then change button to type="submit" and assign the id to its value by value="#item.ItemID".
#foreach (var item in ViewBag.Prod)
{
<form type="POST" action="#Url.Action('AddValue')">
<input type="text" name="Quantity" id="txtQuantity" class="form-control txtQty">
<button name="ID" value="#item.ItemID" type="submit" data-src="#(item.ItemID)" class="btn btn-primary btn-sm" id="btnAddItem-#(item.ItemID)" style="margin-top: 15px;">Add</button>
</form>
}
Then in your controller, add [HttpPost] attribute and since you're not using any model, get the submitted value by accessing Request[name].
[HttpPost]
public ActionResult AddValue()
{
// input
var value = Request["Quantity"];
// button
var value = Request["ID"];
return RedirectToAction("Item");
}
I am new to MVC.NET and I am stopped at some point while passing data from controller to view. I have two action, one is for GET and another is for POST. When I am setting ViewBag values in my POST method action, it redirects me to View but passes the values using GET in the URL hence ViewBag values are not accessible in view.
Here is snapshot of the same:
View:
<div>
<p>#ViewData["FileName"]</p>
<p>#ViewData["myName"]</p>
<p>#ViewBag.myAdd</p>
<p>#ViewBag.someData</p>
</div>
<div>
<form id="myForm" action="~/Test/Index">
<input type="text" name="myName"/>
<input type="text" name="myAdd" />
<input type="file" name="myFile"/>
<input type="submit"/>
</form>
</div>
CONTROLLER
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase file, FormCollection data)
{
ViewBag.FileName = Convert.ToString(file.FileName);
ViewBag.myName = Convert.ToString(data["myName"]);
ViewBag.myAdd = Convert.ToString(data["myAdd"]);
ViewBag.someData = "someData";
return View();
}
On submit of form, it redirects me to http://localhost:65077/Test/Index?myName=mYname&myAdd=MyAdddress&myFile=432f7018-d505-4b0b-8cba-505d62b5472d.png
it would be great if someone can help and explain the same to me.
thanks in advance.
Per default form-data is appended to the URL when send back to the server(GET-method). You have to change this by useing the method attribute:
<form id="myForm" action="~/Test/Index" method="post">
<input type="text" name="myName"/>
<input type="text" name="myAdd" />
<input type="file" name="myFile"/>
<input type="submit"/>
</form>
I'm learning ASP.NET MVC and having a problem with saving a model as below:
Orders -> OrderItems
In my Create view , I will add some items into Order and when I press submit, I want the items data bind to model.OrderItems. How can I achieve this ?
[HttpPost]
public ActionResult Create(OrderViewModel model)
{
...............
//iterate item list and add to main order
foreach (var item in model.OrderItems) <~ this is what I'm trying to do
{
}
...............
}
Thanks a lot.
If they're sequential, you can create an index on each of your inputs:
<input type="text" name="OrderItems[0].Name" value="Stuff" />
<input type="text" name="OrderItems[0].Price" value="5.00" />
...
<input type="text" name="OrderItems[1].Name" value="OtherStuff" />
<input type="text" name="OrderItems[1].Price" value="15.00" />
Or you'll need to provide an index:
<input type="hidden" name="OrderItems.Index" value="#item.ItemId" />
<input type="text" name="OrderItems[#item.ItemId].Name" value="Stuff" />
<input type="text" name="OrderItems[#item.ItemId].Price" value="5.00" />
I have two links say for eg. English and Spanish. When user clicks on english link it should set language to "English" in session.
The following is my aspx code
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
function SetLanguageSpanish() {
document.getElementById("Home_Language").value = 'Spanish';
document.getElementById("frmHome").submit();
}
function SetLanguageEnglish() {
/*var obj = document.getElementById("LangEnglish");*/
// <% Session("Language") = "English"%>;
document.getElementById("Home_Language").value = 'English';
document.getElementById("frmHome").submit();
}
</script>
<div class="vmenu">
<form id="frmHome" action="Home" method="post"">
<a id="LangEnglish" href="/" onclick="SetLanguageEnglish();" >English</a>
<a id="LangSpanish" href="/" onclick="SetLanguageSpanish();"> Spanish</a>
<h3><%= Html.Label(Model.SubTitle) %></h3>
<ul class="sbe">
<li class="sbe"><%= Model.Menu1%></li>
<li class="sbe"><%= Model.Menu2%></li>
<li class="sbe"><%= Model.Menu3%></li>
<li class="sbe"><%= Model.Menu4%></li>
<li class="sbe"><%= Model.Menu5%></li>
</ul>
<input id="Home_PageName" name="PageName" type="hidden" value="" />
<input id="Home_Language" name="Language" type="hidden" value="" />
<input id="Home_PageTitle" name="PageTitle" type="hidden" value="" />
<input id="Home_SubTitle" name="SubTitle" type="hidden" value="" />
<input id="Home_Menu1" name="Menu1" type="hidden" value="" />
<input id="Home_Menu2" name="Menu2" type="hidden" value="" />
<input id="Home_Menu3" name="Menu3" type="hidden" value="" />
<input id="Home_Menu4" name="Menu4" type="hidden" value="" />
<input id="Home_Menu5" name="Menu5" type="hidden" value="" />
</form>
</div>
</asp:Content>
and my controller class code is as follow:
Public Class HomeController
Inherits System.Web.Mvc.Controller
' GET: /Home
<OutputCache(Duration:=1800, VaryByParam:="none")>
Function Index() As ActionResult
Try
Dim oHome As New Home.Home
Dim oHomeModel As New Home.HomeVM
If (HttpContext.Session("Language") Is Nothing) Then
HttpContext.Session("Language") = "English"
End If
oHomeModel.Language = HttpContext.Session("Language").ToString()
Return View("Index", GetCaption(oHomeModel))
Catch ex As Exception
Return Nothing
End Try
End Function
<HttpPost()>
<OutputCache(Duration:=1800)>
Function Index(ByVal oHomeModel As Home.HomeVM) As ActionResult
Try
If ((oHomeModel.Language IsNot Nothing) Or (oHomeModel.Language.ToString() <> "")) Then
HttpContext.Session("Language") = oHomeModel.Language.ToString()
End If
Return View("Index", GetCaption(oHomeModel))
Catch ex As Exception
Return Nothing
End Try
End Function
For some reason when i click on any link on my view page. The Controller class get is getting fired. due to this the value in session is not getting refreshed. Can anyone suggest why this is happening?
The following is my model class.
Namespace Home
Public Class HomeVM
'The following property are used as parameter
Public Property PageName As String
Public Property Language As String
'The following are the form caption peroperty
Public Property PageTitle As String
Public Property SubTitle As String
Public Property Menu1 As String
Public Property Menu2 As String
Public Property Menu3 As String
Public Property Menu4 As String
Public Property Menu5 As String
End Class
It looks to me like you are mixing up server side and client side code.
<% Session("Language") = "English"%>;
The above line you have in JavaScript gets executed when the page first loads which prints nothing to the page. If you look at the source you should see nothing other than the semi-colon ;.
When you click the link that calls SetLanguageSpanish() there is nothing to be executed in that function and the page is directed to '/'. Have a look at the page source.
Edit
Here is some updated code which will submit a hidden input with the id "language" and a value of the specified by the function parameter.
HTML
<form id="frmHome" method="post">
English
Spanish
<input type="hidden" id="language" name="language" value="" />
</form>
JavaScript
function SetLanguage(language) {
document.getElementById("language").value = language;
document.getElementById("frmHome").submit();
}
VB.NET I am not a VB guy so double check the syntax here
<HttpPost()>
<OutputCache(Duration:=1800)>
Function Index(ByVal language As string) As ActionResult
HttpContext.Session("Language") = language
'Do stuff
Return this.View()
End Function
I have a form that has a hidden field wich stores a object. This object is a RoutesValues (I want to store a reference because when I process the form I want to redirect to a route). The action that processes the form is:
public ActionResult Añadir(string userName, string codigoArticulo, string resultAction, string resultController, object resultRouteValues, int cantidad)
{
processForm(codigoArticulo, cantidad);
if (!ModelState.IsValid)
TempData["Error"] = #ErrorStrings.CantidadMayorQue0;
if (!string.IsNullOrWhiteSpace(resultAction) && !string.IsNullOrWhiteSpace(resultController))
return RedirectToAction(resultAction, resultController, resultRouteValues);
return RedirectToAction("Index", "Busqueda", new {Area = ""});
}
and my form is:
#using (Html.BeginForm("Añadir", "Carrito", FormMethod.Get, new { #class = "afegidorCarrito" }))
{
<fieldset>
<input type="hidden" name="codigoArticulo" value="#Model.CodiArticle" />
<input type="hidden" name="resultController" value="#Model.Controller" />
<input type="hidden" name="resultAction" value="#Model.Action" />
<input type="hidden" name="resultRouteValues" value="#Model.RouteValues" />
<input type="text" name="cantidad" value="1" class="anadirCantidad" />
<input type="submit" />
</fieldset>
}
the problem I have is that resultRouteValues gets passed as a string instead of an object. Is there any way to fix this?
Thanks.
No, there is no easy way if RouteValues is a complex object. You will have to serialize the object into some text representation into this hidden field and then deserialize it back in your controller action. You may take a look at MvcContrib's Html.Serialize helper.