MVC4 get table data from view to controller - c#

How can I get the data which is bottom left hand side of the image from view to controller when I press to submit button ?
Link for image
public ActionResult EnterInformation1()
{
// the ??? is the data from the view;
TempData['abc'] = ???
return RedirectToAction("Paper");
}
I did look up reference before I ask.thanks

If you want to send data from view to controller all you need is to do next step:
1) Send data from controller to view. For example you want to display the content of a model wich is List
public ActionResult ShowList()
{
List<string> lst = new List<string>() {"1", "2", "3", ,"4"};
return View("MyListView", lst);
}
2) Display this data on the View using html helpers with postfix "for" (for example, textBoxFor, hiddenFor, EditorFor, DisplayFor...) and place them inside form tag
#model List<string>
<form action="GetDataFromView" method="post">
<table>
<tr>
<th>some header</th>
<tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(m=> item)
</td>
</tr>
}
</table>
</form>
3) Write Method in controller wich will get these data
public ActionResult GetDataFromView(List<string> model)
{
//do what you want with data sended from view to controller
// which stored in parameter model
return View("someView");
}

Related

See ASP.NET MVC Index page in C# be populated with data from model without ID in the URL

In my application I am using Entity Framework 6 and ASP.NET MVC in C#.
I have a table that has records that I plan on populating my Index page with. How do I populate the index page without having the system add the id of the record to the URL. See example below. I have already looked at routing but with adding custom route you are forced to add more text to the url when all I want is the URL to show up as example.com. I don't want and don't need example.com/MenuRecords/Details/20 for a user to see.
So example.com should load the following data from the model below in the index view of the HomeController.
index.cshtml page calling the model data shown below:
#model example.Models.tblMenuRecords
#Model.ThisWeeksBestDrink
#Model.ThisWeeksBestAppetizer
#Model.ThisWeeksBestDesert
#Model.ThisWeeksBestLunchSpecial
This is the cntroller action method:
public ActionResult Index()
{
return View();
}
How do I get that to work properly for the Index page? Since this is the home page that is calling data from a model I cannot have the URL have anything other than example.com .... but I do understand that when calling data from a model you do need some sort of ID but I just do not really understand how to do that.
I know that there is the route config that includes this default route that allows you to show only the name of the domain...But how is this done when you are trying to load data from the database.
routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }
Is this the correct way to pass an instance of the tblMenuRecords to the view?
public ActionResult Index()
{
tblMenuRecords tblMenuRecords = db.tblMenuRecords();
return View(tblMenuRecords);
}
I think you have to fix the action
public ActionResult Index()
{
tblMenuRecords tblMenuRecords = db.tblMenuRecords.FirstOrDefault();
return View(tblMenuRecords);
}
I think your view is missed with model. View code should be like below
#model Models.MenuRecords
#{
ViewBag.Title = "Menu Records";
}
<h2>Details</h2>
<div>
<h4>Menus</h4>
<hr />
<table>
<tr>
<td>
#Html.DisplayFor(model => model.ThisWeeksBestDrink)
</td>
<td>
#Html.DisplayFor(model => model.ThisWeeksBestLunchSpecial)
</td>
</tr>
</table>
</div>
I hope, it will help you.

Create custom dynamic link on form that directs to another page

I am attempting to create a list of items and when the user clicks on the link, it passes the tank serial number to the next form.
Here is what I have so far but how do I make it linkable and pass a tank serial to the next page:
My TankList in my controller:
public ActionResult TankList()
{
var tanklist = new List<string>();
tanklist.Add("1234566777");
tanklist.Add("62523456345");
tanklist.Add("8924545454");
tanklist.Add("34556855433");
tanklist.Add("933456643437");
ViewBag.TankList = tanklist;
return View();
}
My TankList.cshtml:
#{
ViewBag.Title = "Tanks Serial Numbers";
}
<h2>#ViewBag.Title.</h2>
<h3>#ViewBag.Message</h3>
<p>Please select the tank that you wish to administer:</p>
<div>
#foreach (var list in ViewBag.Tanklist)
{
#list
<br />
}
</div>
I wanted to clarify that the above seems to work, at least it creates the link correctly:
My AsmeBasic ActionResult in my controller:
public ActionResult AsmeBasic(string tankserial)
{
ViewBag.TankSerial = tankserial;
return View();
}
The list is being populated but the serial number is not being passed. I'm getting a null value for tankserial.
Ok you need to add a couple things in your HTML.
#foreach (var list in ViewBag.Tanklist)
{
#list
<br />
}
You can also use tag helpers to make it easier.
#foreach (var list in ViewBag.Tanklist)
{
<a asp-action="AsmeBasic" asp-route-tankserial="#list">#list</a>
<br />
}
It looks like you have format issue.
You can use Html.ActionLink helper method to generate the hyper link which will take care of adding the query string parameter in it's correct format:
#foreach (var list in ViewBag.Tanklist)
{
#Html.ActionLink(list, // <-- Link text
"AsmeBasic", // <-- Action Method Name
"Forms", // <-- Controller Name
new { tankserial = list }, // <-- Route value
null // <-- htmlArguments
)
<br />
}

Returning a Model to View from Action

I am new to ASP.NET MVC Web Applications.
I am getting the following Error when I try to access:
http://localhost:1160/View/ViewMovies
ViewMovies is an Action that returns a Model to View. Likewise, I have a similar Action named ViewCustomers, which is also giving me the same error.
Error
ViewController.cs
public class ViewController : Controller
{
// GET: View
public ActionResult Index()
{
return View();
}
private MovieCustomerViewModel model = new MovieCustomerViewModel();
public ActionResult ViewMovies()
{
model.movies = new List<Movie> {
new Movie{id=1,name="Shrek"},
new Movie{id=1,name="Wall-e"}
};
return View(model);
}
public ActionResult ViewCustomers()
{
model.customers = new List<Customer> {
new Customer{id=1,name="Junaid"},
new Customer{id=1,name="Zohaib"}
};
return View(model);
}
}
I have added a view folder named Movie_Customer:
It has two separate .cshtml files named, Customers.cshtml and Movies.cshtml
Customers.cshtml
#model Ex1.ViewModels.MovieCustomerViewModel
#{
ViewBag.Title = "Customers";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Customers</h2>
<table class="table table-bordered table-hover" />
<tr>
<th>ID</th>
<th>Name</th>
</tr>
#{
foreach (var v in Model.customers)
{
<tr>
<td>v.id</td>
<td>v.name</td>
</tr>
}
}
Movies.cshtml
#model Ex1.ViewModels.MovieCustomerViewModel
#{
ViewBag.Title = "Movies";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Movies</h2>
<table class="table table-bordered table-hover" />
<tr>
<th>ID</th>
<th>Name</th>
</tr>
#{
foreach (var v in Model.movies)
{
<tr>
<td>v.id</td>
<td>v.name</td>
</tr>
}
}
I am doing exactly what's done here: http://techfunda.com/howto/240/return-model-to-view-from-action-method
What am I doing wrong?
How do I remove these errors?
What should I must know about handling Views or View Models?
Thanks in advance.
Your controller is named ViewController and by convention the framework will check the ~Views/<ControllerNamePrefix>/ directory and Views/Shared/ directory for a view file matching the name that youre requesting (here you're requesting ViewCustomers and ViewMovies since you are using return View(model) the framework will look for a view with a name that matches the action. If you want to specify the name of the view then use return View("ViewName", model))
To resolve your error, you can rename your view to ViewCustomers.cshtml and ViewMovies.cshtml and put those files in a new directory: location /Views/View/.
Personally, I'd recommend renaming your controller as well since ViewController doesn't really say anything about what the controller should be responsible for. In MVC applications, most all controllers will be returning views.
In summary:
You're requesting views named ViewCustomers.cshtml and ViewMovies.cshtml which don't exist in any folder.
Your views are not located in the write
subdirectory in the Views folder for the framework to be able to find
them.
I think you are confused because when trying to return a view from controller you have to take the literal name and place it in the return overflow as
return View("Customer",model)
Or when constructing a controller you might want right click the name of the controller and select the option "Create view" for the selected controller, this would automatically bind those two together.
Views don't share the same naming convention as controllers

Best way to handle add/view/delete on one page

What I want to do
I am very new to MVC.
I'm trying to create a page that allows users to perform the following actions on the same page:
View the list (table)
Add a new item (Filling the form and clicking the Add button should update the table)
Delete an item from the list (Clicking the Delete button in a row should update the table)
A simple example looks like this but I actually have two lists on one page (Fees and Costs):
Question
What would be the best way to achieve this?
Should I go with Dylan Beattie's method posted here which would look something like this?
public ActionResult MyAction(string submitButton, MyViewModel form)
{
switch (submitButton)
{
case "AddFee":
return (AddFee(form));
case "AddCost":
return (AddCost(form));
case "RemoveFee":
return (RemoveFee(form));
case "RemoveCost":
return (RemoveCost(form));
}
}
public ActionResult AddFee(MyViewModel form)
{
Fee newFee = ....; // Get entered data from `form`
_repository.InsertFee(newFee);
return View("Create"); //Back to the original page
}
Or is there any other recommended methods to handle this such as using JavaScript?
You could create the table as a partial view and re render this via ajax.
Wrap the partial view in a div and Wrap the form in #using (Ajax.BeginForm(.... and target the wrapper div. Your controller action that is targeted by the ajax request will need to return a partial view.
Here is a simple example
public class HomeController : Controller
{
public ActionResult Index()
{
MYvm vm = new MYvm() { id = 1, name = "This is my View Model" };
return View(vm);
}
public ActionResult DA(MYvm vm)
{
vm.name = "CHANGED";
return PartialView("Part", vm);
}
View:
#model MvcApplication1.Controllers.HomeController.MYvm
#{
ViewBag.Title = "Home Page";
}
#using (Ajax.BeginForm("DA", "Home", new AjaxOptions() { UpdateTargetId = "cont", HttpMethod = "Get" }))
{
<div>
Id: #Html.EditorFor(model => model.id)
</div>
<div>
Name: #Html.EditorFor(model => model.name)
</div>
<input type="submit" value="SubmitForm" />
}
<div id="cont">
#{Html.RenderPartial("part", Model);}
</div>
Partial View
#model MvcApplication1.Controllers.HomeController.MYvm
#{
ViewBag.Title = "part";
}
<h2>part</h2>
#Model.name
Should I go with [previous SO answer]
No. That answer was for a different scenario where the question had a form with two submit buttons that wanted to do two different actions (and wasn't even the accepted answer to that question).
Your sample screenshot indicates that some javascript/jquery and ajax would solve the issue cleanly.
As you're new to MVC, try to keep it relatively simple. Break up the page into separate parts:
the containing page
the edit form
the list with remove
the edit/list work independently and should be written in a way that they could be put on any other page - the page is just there to contain them and doesn't do much else (obviously your real page will contain more, but add those parts as separate components as well).
1 Create actions for your list and edit forms that return partialviews - just the parts that are needed for that view (self-contained)
controller:
[HttpGet]
public ActionResult AddCost()
{
var model = new Cost();
return PartialView(model);
}
[HttpPost]
public void AddCost(Cost model)
{
if (ModelState.IsValid) {
db.SaveCost(model);...
}
}
form Views/Home/AddCost.cshtml:
#using (Ajax.BeginForm(...
{
<div class='editor-label'>#Html.LabelFor(model=>model.Description)</div>
...etc...
}
I'll leave you to set the Ajax.BeginForm properties. But make sure the on-success calls reloadCostList() (see below)
controller
public ActionResult CostList()
{
var model = db.loadCosts(); ...
return PartialView(model);
}
list, Views/Home/CostList.cshtml
#model IEnumerable<ViewModels.Cost>
<table>
<thead>
<tr>
<th>Cost Description</th>
...
<tbody>
#foreach (var cost in Model.Costs)
{
<tr data-id='#cost.Id'>
<td>#Html.DisplayFor(x=>cost.Description)</td>
...
<td><a href='#' class='remove-button'>Remove</a></td>
}
...
2 Create an action + view for the main page with placeholder for the form and calls the list partial-action, eg:
<div id="body">
<div id="formWrapper">
#Html.Action("AddCost")
</div>
<div id="listWrapper">
#Html.Action("ListView")
</div>
</div>
if you already load the data for the page, you can pass it directly to the partial, but there's no need:
#Html.Partial("ListView", Model.Costs)
this allows you to refresh the list via an ajax call, something like:
function reloadCostList() {
$(".listWrapper").load("Home/CostList");
}
(ideally, $.ajax and add some fancy UI to indicate loading)
3 Add a remove action to your controller
[HttpPost]
public void RemoveCost(int id)
{
}
4 Wire up the Remove link
$(function() {
$(".remove-button").click(function() {
var id = $(this).closest("tr").attr("id");
$.post("/Home/RemoveCost/" + id, null, function() {
$(".listWrapper").load("Home/CostList");
// or reloadCostList(); from above
// or:
//$(".listWrapper tr[id=" + id + "]").hide();
});
});
}
rather than re-load the entire list, you could just remove the row (add some fancy UI like fade-out...)

How to save Files content in Database table with File type in Asp.net MVC

I have table 'Artifact' with columns
ID File Type CONTENT
1 Experience Certifacte Some data in varbinary type
In UI, i have one row in html table which was one column was'drop down list' file type contains items of file types like Experience certificate, Appreciation Certificate etc., and one 'upload file' control..
dropdownlist <input type="file"/>
dropdownlist <input type="file/>
etc.,......................
.............................
And one button to add more files , which adds same above row.
Now I want to Insert multiple files content with file type.
I can Insert multiple files content in 'CONTENT' column in Artifact table like
[HttpPost]
public ActionResult FileUpload(IEnumerable<HttpPostedFileBase> file_Uploader)
{
if (file_Uploader != null && file_Uploader.ContentLength > 0)
{
foreach(var item in file_Uploader)
{
var content = new byte[item .ContentLength];
item .InputStream.Read(content, 0, file_Uploader.ContentLength);
var document= reslandEntities.ARTIFACT.Where(m => m.ID == 1).SingleOrDefault();
document.CONTENT = item.ToArray();
document.filetype= ?? // How to save file type with same file
reslandEntities.SaveChanges();
}
}
}
But the Problem is , How to save files content with drop down list file types,i mean, how to get the file types and save with same row with file content in database table?
Anybody have idea? Please help me?
Try to Pass Model to HttpPost Method Like this
[HttpPost]
public ActionResult FileUpload(IEnumerable<HttpPostedFileBase> file_Uploader, ClassName Model)
{
if (file_Uploader != null && file_Uploader.ContentLength > 0)
{
foreach(var item in file_Uploader)
{
var content = new byte[item .ContentLength];
item .InputStream.Read(content, 0, file_Uploader.ContentLength);
var document= reslandEntities.ARTIFACT.Where(m => m.ID == 1).SingleOrDefault();
document.CONTENT = item.ToArray();
document.filetype=Model.dropdownlistID;
}
reslandEntities.SaveChanges();
}
}
}
I got it.
Just Add Property in the model as
public class EmployeeModel
{
public int ArtifactId { get; set; } //For Dropdown list
public HttpPostedFileBase FileContent { get; set; } // For uploading file.
}
in View
#using (Html.BeginForm("GetFiles", "Home", FormMethod.Post, new { enctype = "multipart/form-data", #class="form" }))
{
<table>
<tr>
<td>#Html.DropDownListFor(m => m.ArtifactId, Model.getDocumenttype())</td>
<td>#Html.TextBoxFor(m => m.FileContent, new { #type = "file" })</td>
</tr>
<tr>
<td><input type="button" value="submit" id="btnSave" /></td>
</tr>
</table>
}
and for Controller Acton method
[HttpPost]
public ActionResult GetFiles(EmployeeModel model)
{
return View();
}
I have got the solution as above.
But, is it possible to send model using jquery like
var model = $('.form').serialize();
i have tried , but not getting.

Categories

Resources