from data to controller and passing it to form - asp.net-mvc

I'm doing my first steps in mvc and I need help.
I'm passing data from view to this controller and I need to pass the selected items with there details to a different view (that is a form that the user add his email details) and I cant figure out how to .
This is how I'm getting the details to the controller from the submitted form
public ActionResult list()
{
var AllItems = db.menu.ToList();
Mapper.CreateMap<Menu, SelectableMenu>();
return View(AllItems.Select(m => new SelectableMenu { price = m.price, MenuId = m.MenuId, Name = m.Name })
.ToList());
}
[HttpPost]
public ActionResult List(IEnumerable<SelectableMenu> item)
{
var userSelectedMenu = item.Where(m => m.IsSelected).Select(m => m.Name + m.price + m.MenuId);
if (userSelectedMenu != null && userSelectedMenu.Any())
{
return View("bla");
}
return View();
}

Use method ReditectToActionstring actionName, string controllerName, Object routeValues)
for details go to: http://msdn.microsoft.com/en-us/library/dd460311(v=vs.108).aspx

You can return different view using return View("ViewName",model)
For eg:
[HttpPost]
public ActionResult List(IEnumerable<SelectableMenu> item)
{
var userSelectedMenu = item.Where(m => m.IsSelected).Select(m => m.Name + m.price + m.MenuId);
if (userSelectedMenu != null && userSelectedMenu.Any())
{
return View("YourDiffrentViewName",userSelectedMenu); // This will pass your model to your Different view
}
return View();
}
Then in your new view you will have to strongly typed it with your model.
For eg :
Your view will be as follows:
#model ProjectName.models.YourClassName //Your class/model namespace
#using(Html.BeginForm())
{
#Html.TextBoxFor(m => Model.Property) //This will create textbox for your property
<input type="submit" value="Submit" />
}
For more on stronly typed views visit:
http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/strongly-typed-views-in-mvc/
http://www.howmvcworks.net/OnViews/BuildingAStronglyTypedView

You will need twosteps for this
Step 1
Make a model(it is more effective) use it in a view to pass your data to controller through post in submission of form.
Step 2
Receive the data into the controller method then use
return View("yourNewpage","yourdatamodelobject"); in the controller action to pass the data in the action result view of another page.
Alternatively, if the view is in another controller
then you can receive data here in the post action method and use Return RedirectToAction("ActionName", "ControllerName", "DataModelObject") to pass to a diffrent controller

Related

Trying To pass list of data in from controller to partial view in mvc

I am trying to pass list of data through viewbag from controller to partial view but getting error
in login form after submitting data taking it from formcollection through HttPost and once action complete it return to home page from there i am calling method Page_Init inside that in 'loadmessage' method i am trying to return list to a partial view "Header" based on condition.but not able to perform getting error
Home controller
[HttpPost]
public ActionResult Login(FormCollection form)
{
return View("Home");
}
in Home.cshtml
calling method page_init in controller
$.get("/Home/Page_Init",null, function (data) {
alert(data);
});
Home controller
public ActionResult Page_Init()
{
loadMessages();
return view("Home");
}
public ActionResult loadMessages()
{
List<MessageModel> lstMessages = new List<MessageModel>();
List<MessageModel> lstInfoMessages = new List<MessageModel>();
lstInfoMessages = lstMessages.Where(msg => msg.MESSAGE_TYPE.Equals(CommonConstants.SAFETY_MESSAGE_INFO, StringComparison.InvariantCultureIgnoreCase)).ToList<MessageModel>();
if (lstInfoMessages.Count > 0)
{
ViewBag.lstInfoMessages = 1;
ViewBag.lstInfoMessages1 = lstInfoMessages;
return PartialView("Header", lstInfoMessages);
}
}
also trying to go to partial view from Home view
#ViewBag.lstInfoMessages1
#if (ViewBag.lstInfoMessages == 1)
{
#Html.Partial("Header",ViewBag.lstInfoMessages1)
}
Expected that list of information should go to partial view and bind
Error:Not getting Exact syntax what to do and how to proceed the steps tried above throw error
#Html.Partial method does not accept the dynamic value – so we need to cast it to the actual type.
#model MessageModel //you need to give correct path of MessageModel
#ViewBag.lstInfoMessages1
#if (ViewBag.lstInfoMessages == 1)
{
#Html.Partial("Header", (List<MessageModel>)ViewBag.lstInfoMessages1)
}
In Header Partial view, you can retrieve list using #Model

Calling a partial view in mvc3

This might be a duplicate title but I have a different question. I have this code
public ActionResult _FieldAssignmentView()
{
Shift shift = new Shift();
Person person = new Person();
Signatory sig = new Signatory();
ViewBag.ShiftId = new SelectList(db.Shifts, "ShiftId", "ShiftDesc", shift.ShiftId);
var empid = (from p in db.People join s1 in db.Employees on p.PersonId equals s1.PersonId select new { CompleteName = p.CompleteName, s1.EmployeeId });
ViewBag.EmployeeID = new SelectList(empid, "EmployeeId", "CompleteName", null).OrderBy(m => m.Text);
if (Roles.IsUserInRole(User.Identity.Name, "divisionhead") && Roles.IsUserInRole(User.Identity.Name, "director"))
{
return PartialView("_FieldAssignment");
}
else
{
return PartialView("_FieldAssignmentForEmployee");
}
// return View();
}
Now my question it is possible to return two(2) partial view?.
I have four partial views (1,2,3,4) and I duplicate the view 1 and 4 for the employee log.in to disabled a certain button. For example the employee will log.in view 1 and 4 will return in my else code.
If possible how?. Thanks.
For example the employee will log.in view 1 and 4 will return in my
else code. If possible how?
You can create another container partial view in which you include the other 2 partial views.
LoggedInUserView.cshtml
#Html.Partial("_FieldAssignment")
#Html.Partial("_FieldAssignmentForEmployee")
Now in your else condition, you can return this view
return PartialView("LoggedInUserView.cshtml");
If you want to disable a button in any of these views, You can add a boolean property to your view model and set the value in your action method and use that to conditionally show a disabled/enabled button
public class FieldAssignmentViewModel
{
public bool IsAllowedToAssign {set;get;}
}
and in your action method,
var vm = new FieldAssignmentViewModel();
vm.IsAllowedToAssign = true; // Set this value based on your custom condition.
return View(vm);
Now, the view you are passing this object should be strongly typed to our view model.
_FieldAssignment.cshtml
#model FieldAssignmentViewModel
#using(Html.BeginForm())
{
#if(Model.IsAllowedToAssign)
{
<input type="submit" value="Assign" />
}
else
{
<input type="button" disabled value="Assign" />
}
}

How to pass a list in a get request

I have an url that works for passing a List of strings
/Home/Index?Person%5B0%5D=Myname&Person%5B1%5D=Yourname
Unencoded it is
/Home/Index?Person[0]=Myname&Person[1]=Yourname
The Action Method is
public ActionResult(List<string> person)
{
...
}
The Parameter List person will be correctly filled with the values Myname and Yourname.
I need to redirect to this url using RedirectToAction
I would usually do
RedirectToAction("Index","Home",new {Parameter1=value1})
But obviously I cant use Person%5B0%5D as a parameter name, because it has ivalid characters.
How can I create such a link or should I use a different URL - scheme?
hi i worked on your query and finally got the result just check this code find weather it work with your query.
Controller code :
public ActionResult showString()
{
try
{
IEnumerable<string> persons = new[] { "myname", "urname" };
var values = new RouteValueDictionary(
persons
.Select((sampleper, index) => new {sampleper, index })
.ToDictionary(
key => string.Format("[{0}]", key.index),
value => (object)value.sampleper
)
);
return RedirectToAction("details", values);
}
catch (Exception)
{
throw;
}
}
and another action method is details with list as parameter
public ActionResult details(IEnumerable<string> persons)
{
ViewBag.person = persons;
return View();
}
it also works if you pass the link as
http://localhost:2266/Home/details?%5B0%5D=myname&%5B1%5D=urname
the view of details action method is
#{
ViewBag.Title = "details";
}
<h2>details</h2>
<ul>
#foreach (var i in ViewBag.person)
{
<li>#i</li>
}
</ul>

Foreach does not work while using json in asp.net mvc

,Hi all,
I am trying to use json.İf ı return to partial view ,i can not use foreach for my customer session.My Customer Session has customers.I can not list them.
Where i miss ?
CONTROLLER:
public ActionResult ShowResult(MyModel model)
{
Session["CustomerList"] = context.Customer.Where(s => s.CustomerSituation== true).ToList(); // Customers List To Session
var stringView = RenderRazorViewToString("_ShowResultPartial", model);
return Json(stringView, JsonRequestBehavior.AllowGet);
}
.
My _ShowResultPartial View:
#foreach (var item in (List<Q502351.Models.Customer>)Session["CustomerList"])
{
Ajax.ActionLink(item.CustomerName, "ShowResult", new { CustomerId = item.CustomerId}, new AjaxOptions { HttpMethod = "POST" });
}
From what you have posted, it's not clear why you want to store the customer list in session; data for the view should generally be stored on the view model. Even if you have a compelling reason to use session, it's a better practice to retrieve the session variables in the controller and store them in the view model. Then you should be able to loop through the list on the model from the view. In this situation it doesn't look like session is necessary at all (unless you intend to reuse the stored data later and for some reason cannot pass it along via models).
Also, unless there is a good reason to return json, your ShowResult controller method should just return a PartialView.
Something like this should work...
Controller:
public ActionResult ShowResult(MyModel model)
{
model.Customers = context.Customer.Where(s => s.CustomerSituation == true).ToList();
return PartialView("_ShowResultPartial"), model);
}
Partial view:
#model MyModel
#foreach (var item in Model.Customers)
{
Ajax.ActionLink(item.CustomerName, "ShowResult", new { CustomerId = item.CustomerId}, new AjaxOptions { HttpMethod = "POST" });
}

accessing viewbag in the view

net MVC. I have assigned a list of objects to the viewbag property can anyone please tell me as to how i can get the list in the view to use it in the drop down list? here is my controller code & view code
Controller:
public ActionResult GetSection(int sectionId,int contactId)
{
ContactDetailSectionModel contactDetailSection = new ContactDetailSectionModel { SectionId = sectionId,ContactId=contactId };
contactDetailSection.FetchAllSubsections();
ContactDetailSectionModel customSections = new ContactDetailSectionModel();
customSections.FetchCustomSubSections();
if(customSections != null && customSections.ContactDetailSubSections != null)
{
ViewBag.CustomSubSections = customSections.ContactDetailSubSections;
}
return PartialView("~/Views/Contacts/Details/EditSection.cshtml", contactDetailSection);
}
View Code:
#Html.DropDownListFor(m => m.ContactDetailSubSections[1], new SelectList(ViewBag.CustomSubSections , "Name", "Name",Model.ContactDetailSubSections[1].Name))
#Html.TextAreaFor(m => m.ContactDetailSubSections[1].Text)
I think the first parameter in your #Html.DropDownlist should be string or some scalar quantity it cannot be a collection.

Resources