How Using tempdata to pass data entered by user in a data field from view to another view - asp.net-mvc-5

I am new to MVC. I one please help me on how to assign value entered by user (for instance table column such as username) in a view to TempData.
I also want to pass the assigned data to a column in another view

In your view, add a form field:
<input name="myfield" type="text" />
In your controller's action, get the field and store it in TempData:
public ActionResult ProcessIt(string myfield)
{
TempData["yourkey"] = myfield;
return RedirectToAction("SomeOtherAction");
}
Now you can use it in the SomeOtherAction view:
<div>Entered data: #TempData["yourkey"]</div>

Thanks, I am creating web test, the controller for the question
public async Task Create([Bind(Include = "QuestionID,Question")]
TestQuestion testQuestion, string command, FormCollection QuestionData)
{
if (ModelState.IsValid)
{
db.TestQuestions.Add(testQuestion);
await db.SaveChangesAsync();
return RedirectToAction("Create", "TestOptions");
}
The controller for the options:
public async Task Create([Bind(Include = "OptionID,QuestionID,OptionA")] TestOption testOption)
{
if (ModelState.IsValid)
{
db.TestOptions.Add(testOption);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.QuestionID = new SelectList(db.TestQuestions, "", "", testOption.QuestionID);
return View(testOption);
}
I desire to display the question just entered by the user in the Create method of the option controller so that the user would enter the options for question.
The program create a dropdownlist of all the questions l've enter before, but I want only the last question should show in the redirected view.

Related

#html.dropdown onchange event MVC5

I have a View with a dropdownlist. I would like to select a value from the dropdownlist and depending on that value pull into the View a form related to that selection.
Looks like this:
I would like the form to appear below this ddlist and if the user changes the value in the ddlist, it would change the form.
Here's my "Add" View:
<div id="matSelContainer">
#Html.Action("SelectMaterial", "Materials", "Materials")
</div>
Here's the "SelectMaterial" View:
#model Procurement.Models.Material.MaterialType
#Html.Label("Select a Material Type: ")
#Html.DropDownListFor(
x => x.MaterialTypeList,
new SelectList(Model.MaterialTypeList, "MaterialTypeId", "Name")
)
Here's my Controller:
public ActionResult Add()
{
return View();
}
public ActionResult SelectMaterial()
{
materialTypes.LoadMaterialTypes();
return PartialView(materialTypes);
}
I would like to have a separate View for each Material Type and just call that View based on the selection in the ddlist.
Can someone show me how to achieve this?
Would I add a separate #Html.Action to the "Add" View and then in the Controller have another action return a PartialView?
But how to connect this with the Onchange event?
Update<<
Here's what is almost working for me:
"SelectMaterial" View:
#model Procurement.Models.Material.MaterialType
#Html.Label("Select a Material Type: ")
#Html.DropDownListFor(
x => x.MaterialTypeList,
new SelectList(Model.MaterialTypeList, "MaterialTypeId", "Name"),
new { #onchange="CallChangefunc(this.value)" })
<script>
function CallChangefunc(val) {
//alert("i am a " + obj.options[obj.selectedIndex].text);
//alert(obj.options[obj.selectedIndex].text);
window.location.href = "/Materials/MyMethod/" + val;
}
</script>
In my Controller I have this ActionResult:
public ActionResult MyMethod(string value)
{
return PartialView();
}
My controller is getting called when I change selection but the value coming in is null. I can see on the browser address bar that the expected selected value is being passed. Why is it null in controller? (I tried adding an [HttpPost] to ActionResult with no luck.)

Delete function doesn't work in MVC application-Does not delete from DB?

I'm trying to make a delete function in my application that the user should be able to delete a product from the table but when the user presses the delete button, the error message "InvalidOperationException: Cannot remove an entity that has not been attached" comes up. I can't figure out what the problem is because it get's the product the user want's to delete(and displays it in the view) but when it get's to the HttpPost method, (when the user confirms that he want's to delete this product by pressing the delete button), the error message comes up... All the other methods work(create,edit,list...)only the delete method doesn't. I would really appreciate if someone can help me with this.
this is my code:
[HttpGet]
public ActionResult Delete(int id)
{
var p= prodRepo.GetProductById(id);
return View(p);
}
[HttpPost]
public ActionResult Delete(Product product)
{
prodRepo.DeleteProduct(product);
return RedirectToAction("Index");
}
this is the code from the productRepository class...
public Product DeleteProduct(Product product)
{
db = new NorthwindDataContext();
db.Products.DeleteOnSubmit(product);
db.SubmitChanges();
return product;
}
public Product GetProductById(int id)
{
db = new NorthwindDataContext();
var prod = (from p in db.Products
where p.ProductID==id
select p).Single();
return prod;
}
Just pass the id of product in delete action
[HttpPost]
public ActionResult DeleteConfirmed(int id)
{
Product_Table Ptobj = db.Product_Table.find(id);
db.Product_Table.remove(Ptobj);
db.savechanges()
}

Pass #Html.DropDownList selection using #Html.ActionLink with ViewModel to Controller

I've been reading through posts for two days regarding this, and still have not figured out the answer. I want to capture the DropDownList selection within my ModelView, pass this to a #Html.ActionLink, which will send it back to a specific Action within the Controller.
My ViewModel:
public class ViewModelShipments
{
public ViewModelShipments()
{
tblShipments = new tblShipments();
}
public tblShipments tblShipments;
public IEnumerable<SelectListItem> ShipmentIDsList;
public string SelectedShipmentID;
}
My Controller:
public ActionResult SelShipment(string SelectedShipmentID)//for ShipmentID change via DropDownList
{
int id = db.tblShipments.Max(p => p.ShipmentID); // find last ShipmentID
if (SelectedShipmentID != null)
{
id = Int32.Parse(SelectedShipmentID);//convert text to int
}
My View:
#Html.DropDownListFor(expression: model=>model.SelectedShipmentID,selectList: Model.ShipmentIDsList) #* render DropDownList object*#
#Model.SelectedShipmentID #* display value of SelectedShipmentID *#
<!-- Upon Click, send selected ID to controller -->
<!-- the ActionLink is working, but the routeValues: always contain NULL -->
#Html.ActionLink(linkText: "Submit", actionName: "SelShipment", controllerName: "Shipment", routeValues: Model.SelectedShipmentID, htmlAttributes: null)
Why does the ActionLink(..., routeValues: Model.SelectedShipmentID,...) always return NULL to the Controller ? The Model.SelectedShipmentID is not updated with the DropDownList selected id. Please help as I'm running out of time on this.
Razor code is parsed on the server before its sent to the view, so the value of your route parameter will be the initial value of SelectedShipmentID. Selecting a value from a dropdownlist does not change the url you have already rendered.
You could use javascript/jquery to handle the dropdownlist's .change() event (or the links .click() event) to update the url, however the better way to handle this is by using a form that makes a GET to your controller method
#model ViewModelShipments
#using (Html.BeginForm("SelShipment", "Shipment", FormMethod.Get))
{
#Html.DropDownListFor(m => m.SelectedShipmentID, Model.ShipmentIDsList, "-Please select-")
<input type="submit" />
}
Note the last parameter of DropDownListFor() add a label option allowing you to post back null but not sure if this is appropriate for you.
Since your binding to a value which is int then both your model property and method parameter should be int? not string. In additiona you should change the logic in the controller so that you are not making unnecessary database calls when a valid value is passed to the method.
public ActionResult SelShipment(int? SelectedShipmentID)
{
if (!SelectedShipmentID.HasValue)
{
// only necessary to call database if SelectedShipmentID is null
SelectedShipmentID = db.tblShipments.Max(p => p.ShipmentID)
}
....
}
Side note: From your view model properties, I assume you wanting to display some data in the view based on the value of the selected ShipmentID. If so you should consider using ajax to post the selected value to a controller method that returns the tblShipments data based on the value, either as a partial view or as json, and update the current page, rather than doing a complete page refresh each time.

How to attach an existing View to a controller action?

How can I attach an existing View to an Action?
I mean, I've already attached this very View to an Action, but what I want is to attach to a second Action.
Example:
I've an Action named Index and a View, same name, attached to it, right click, add view..., but now, how to attach to a second one? Suppose an Action called Index2, how to achieve this?
Here's the code:
//this Action has Index View attached
public ActionResult Index(int? EntryId)
{
Entry entry = Entry.GetNext(EntryId);
return View(entry);
}
//I want this view Attached to the Index view...
[HttpPost]
public ActionResult Rewind(Entry entry)//...so the model will not be null
{
//Code here
return View(entry);
}
I googled it and cant find an proper answer...
It's possible?
you cannot "attach" actions to views but you can define what view you want be returned by an action method by using Controller.View Method
public ActionResult MyView() {
return View(); //this will return MyView.cshtml
}
public ActionResult TestJsonContent() {
return View("anotherView");
}
http://msdn.microsoft.com/en-us/library/dd460331%28v=vs.98%29.aspx
Does this help? You can use the overload of View to specify a different view:
public class TestController : Controller
{
//
// GET: /Test/
public ActionResult Index()
{
ViewBag.Message = "Hello I'm Mr. Index";
return View();
}
//
// GET: /Test/Index2
public ActionResult Index2()
{
ViewBag.Message = "Hello I'm not Mr. Index, but I get that a lot";
return View("Index");
}
}
Here is the View (Index.cshtml):
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>#ViewBag.Message</p>

ASP.NET MVC 4 Remember page index

In a ASP.NET MVC 4 app I have a view with a paged list (just a simple table, no telerik grid or anything like that). New values are fetched from the database when the user pages through the list.
On every row in that table there is an edit button, when clicking the button you are presented with an edit view and when you click save in that view you are redirected back to the view with the paged list.
The urls for the list view looks like this
http://localhost/Items/Page/1
http://localhost/Items/Page/2
The route looks like this
routes.MapRoute(
name: "ItemsList",
url :"Items/Page/{page}",
defaults: new { controller = "Items", action = "Index", page = 1 },
constraints: new {page = #"\d+"}
);
My question is this: what is the preferred, most common way to store away the referring url, so when done editing an item, I can redirect the user back to the correct url
http://localhost/Items/Page/2
and not just to
http://localhost/Items
I've tried splitting up
Request.UrlReferrer.PathAndQuery
and storing those values around, and then build the url from those values but I have a feeling there is a much better solution to this problem. Any suggestions?
Update
Right now I'm thinking that I could put the UrlReferrer.PathAndQuery (if there are any values) as a property on the view model for the edit screen and then use that when deciding on where to redirect after a save.
Any thoughts out there on that approach?
Here is my final solution to the problem, it's not super elegant but it works.
I added a property to the View model that could store the url. That value get's stored in a hidden field.
public class SkillEditModel
{
public int Id { get; set; }
public string Name { get; set; }
public string RedirectBackToUrl { get; set; }
}
In the controller Edit(GET) method I store the value with the view model
if (!Request.UrlReferrer == null)
{
model.RedirectBackToUrl = Request.UrlReferrer.PathAndQuery;
}
And finally after saving the changes in Edit (POST) I did this
if (!string.IsNullOrWhiteSpace(model.RedirectBackToUrl))
{
return new RedirectResult(model.RedirectBackToUrl);
}
return RedirectToAction("Index");

Resources