I have an issue with passing 2 parameters from view to controller, when assigning them as a button. If I use this code in my View:
#using (Html.BeginForm("Edit", "Shift", new { lineName = item.Line, dateTime=item.Date }))
{
<input type="submit" value="Edit"/>
}
I get this string as result, which doesn't work because ampersand is replaced with &
<form action="/Shift/Edit?lineName=Line%203&dateTime=04%2F01%2F2004%2007%3A00%3A00" method="post"> <input type="submit" value="Edit"/>
</form>
So to resolve that I found I could use the Html.Raw
#using (Html.Raw(Url.Action("Edit", "Shift", new { lineName = item.Line, dateTime=item.Date })))
{
<input type="submit" value="Edit"/>
}
But this give me error:
'System.Web.IHtmlString': type used in a using statement must be implicitly convertible to 'System.IDisposable'
My Controller metdhods: (Edited)
//Displays Edit screen for selected Shift
public ViewResult Edit(string lineName, DateTime dateTime)
{
Shift shift = repository.Shifts.FirstOrDefault(s => s.Line == lineName & s.Date == dateTime);
return View(shift);
}
//Save changes to the Shift
[HttpPost]
public ActionResult Edit(Shift shift)
{
// try to save data to database
try
{
if (ModelState.IsValid)
{
repository.SaveShift(shift);
TempData["message"] = string.Format("{0} has been saved", shift.Date);
return RedirectToAction("Index");
}
else
{
//return to shift view if there is something wrong with the data
return View(shift);
}
}
//Catchs conccurency exception and displays collision values next to the textboxes
catch (DbUpdateConcurrencyException ex)
{
return View(shift);
}
}
Could you please support me with this, I spend couple of days on this one now.
Thanks
According to my understanding of your code, I suggest you following solution:
In View:
#using (Html.BeginForm("Edit", "Shift", FormMethod.Post, new { enctype = "multipart/form-data"}))
{
<input type="hidden" name="lineName" value="#item.Line"/>
<input type="hidden" name="dateTime" value="#item.Date"/>
<input type="submit" value="Edit"/>
}
In Controller :-
[HttpPost]
public ActionResult Edit(datatype lineName , datatype dateTime)
{
}
Please correct me If I am wrong.
add parameter in controller method for eg.
View :-
#using (Html.BeginForm("Edit", "Shift", new { lineName = item.Line, dateTime=item.Date }))
{
<input type="submit" value="Edit"/>
}
Controller :-
public ActionResult yourMethod(datatype lineName , datatype dateTime)
Related
The answer I am sure is simple. I have a <select> with a list of values. For edit mode, I want the drop down to show the current value and have the selected when the view renders. And also when the form is submitted take a possible new selected value and pass it back to the controller. Any help would be greatly appreciated.
From the view:
<td style="padding:15px">
<label asp-for="OrganizationTypeId" class="form-control-label" style="font-weight:bold">Organization</label>
<select asp-for="OrganizationTypeId" class="form-control" style="width:450px" asp-items="#(new SelectList(Model.orgTypes, "Id", "OrganizationName"))">
<option value="" disabled hidden selected>Select Organization....</option>
</select>
</td>
Code in the controller:
dr = _electedOfficials.getDeputyReg(jurisdictionId, Id);
dr.orgTypes = _electedOfficials.GetOrganizationTypes(jurisdictionId);
return View(dr);
OrgTypes class
public int Id { get; set; }
public string OrganizationName { get; set; }
One of the solutions is preparing list of the SelectListItem and return the selected item Id to the controller:
public ActionResult Index()
{
// ...
dr.orgTypes = _electedOfficials.GetOrganizationTypes(jurisdictionId);
var model = dr.orgTypes.Select(d => new SelectListItem() { Selected = (d.Id == /* id of default selection*/), Text = d.OrganizationName, Value = d.Id.ToString() }).ToList();
return View(model);
}
[HttpPost]
public ActionResult Index(int? seletedId)
{
if (ModelState.IsValid && seletedId.HasValue)
{
// Processing the selected value...
}
return RedirectToAction("Index");
}
In the view:
#model IEnumerable<SelectListItem>
<script type="text/javascript">
$(document).ready(function () {
var e = document.getElementById("OrgTypesList");
$("#SeletedId").val(e.options[e.selectedIndex].value);
});
function changefunc(val) {
$("#SeletedId").val($("#OrgTypesList").val());
}
</script>
#using (Html.BeginForm("Index", "Home"))
{
#* To pass `SeletedId` to controller *#
<input id="SeletedId" name="SeletedId" type="hidden" />
<label asp-for="OrganizationTypeId" class="form-control-label" style="font-weight:bold">Organization</label>
#Html.DropDownList("OrgTypesList", Model, "Select Organization...", new { #class = "form-control", #onchange = "changefunc(this.value)" })
<button type="submit" class="btn btn-primary">Save</button>
}
I'm trying to do my first simple file upload in MVC 5. I'm following a bunch of examples I've found but for some reason in my "Create" ActionResult the uploadFile is always coming in as NULL so the upload code is never running. Anyone see what I might be doing wrong?
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Documents.</h2>
<h4>Upload a new document.</h4>
<div class="well">
#using (Html.BeginForm("Create", "Documents", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<h3>Select a file to upload. </h3>
<input type="file" name="files" value="" multiple="multiple" />
<input type="submit" value="Upload your file" title="Upload" />
<div style="color:Red;font-size:14px">#ViewBag.Message</div>
}
</div>
Here is my controller:
// POST: Documents/Create
[HttpPost]
public ActionResult Create(HttpPostedFileBase uploadFile)
{
try
{
if(uploadFile != null && uploadFile.ContentLength > 0)
{
string filePath = Server.MapPath("../SiteDocuments" + uploadFile.FileName);
uploadFile.SaveAs(filePath);
}
return RedirectToAction("Index");
}
catch (Exception ex)
{
return View();
}
}
Your file input element's name should match to your action method parameter name.
So update your HTML markup to have the same name attribute value.
<input type="file" name="uploadFile" value="" multiple="multiple" />
and your action method will be
[HttpPost]
public ActionResult Create(HttpPostedFileBase uploadFile)
{
// do something
}
Or change your action method parameter name to match with your file input element name.
<input type="file" name="files" value="" multiple="multiple" />
and your action method will be
[HttpPost]
public ActionResult Create(HttpPostedFileBase files)
{
if(files!= null && files.ContentLength > 0)
{
// do something
}
}
When you add multiple="multiple" attribute to the input element, the browser will allow the end user to select more than one file at a time. In that case If your action method parameter is a single instance of HttpPostedFileBase object, It will receive the first file from the selected n files. If you want all the files, You may change your parameter to a collection such as
[HttpPost]
public ActionResult Create(IEnumerable<HttpPostedFileBase> files)
{
if (files != null && files.Any())
{
foreach (var file in files)
{
if (file.ContentLength > 0)
{
//do something
}
}
}
}
View:
#using (Html.BeginForm())
{
#Html.Label("WebLinkLabel")
#Html.Editor("WebLinkTextbox")
#Html.Label("WebEnabledLabel")
#Html.CheckBox("WebEnabledCheckbox")
<input name="Save" type="submit" value="Save" />
}
Action Method:
[HttpPost]
public ActionResult Index(FormCollection collection)
{
foreach (var key in collection.AllKeys)
{
var typee = collection.GetType();
}
return View();
}
GetType() gives me that:
collection.AllKeys.GetType()
{Name = "String[]" FullName = "System.String[]"} System.Type {System.RuntimeType}
I would like to know like the first controller is of type Textbox, another one is Checkbox etc..
#using (Html.BeginForm("Orders1", "Track", FormMethod.Post))
{
#Html.TextBox("order")<br />
#Html.TextBox("order")
<input type="submit" value="Submit" />
}
Hello how can i use two text box and pass value to the same parameter? The first textbox work but the other textbox doesn't.
public ActionResult Orders1(IEnumerable<int> order)
{
var query = from a in context.CM_Checkout_Details
where a.CheckoutDetails_ID == order // my error
select a;
return View(query);
}
}
simple solution would be to change your parameter from int to IEnumerable<int>
public ActionResult Orders1(IEnumerable<int> orders)
{
}
can someone tell me if im on the right track? Im trying to display my query but i get an error. I have two textbox with the same parameter and that parameter is declared as an IEnumerable.
[HttpPost]
public ActionResult Orders1(IEnumerable<int> order)
{
using (CostcoEntities1 context = new CostcoEntities1())
{
var query = string.Empty;
foreach (var orderID in order)
{
query = (from a in context.CM_Checkout_Details
where a.CheckoutDetails_ID == orderID
select a).ToString();
}
return View(query);
}
}
this is what my controller looks like..
I am trying to read the two numbers(Id) in the text box and diplay data based on those id.
#using (Html.BeginForm("Orders1", "Track", FormMethod.Post))
{
#Html.TextBox("order")<br />
#Html.TextBox("order")
<input type="submit" value="Submit" />
}
First thing, change the names of the textboxes so that they are not the same:
#using (Html.BeginForm("Orders1", "Track", FormMethod.Post))
{
#Html.TextBox("order1")<br />
#Html.TextBox("order2")
<input type="submit" value="Submit" />
}
Next, change the signature of your action method:
[HttpPost]
public ActionResult Orders1(string order1, string order2)
MVC's model binding will try to match order1 and order2 to stuff in Request.Form, for example, which should pick up the textbox values.