I am learning mvc 4. Im new to mvc and i had implement ajax call for passing parameters and
I have one List shown in below:
[HttpPost]
public List<Reportdata> ReportTransaction(string dfromdate, string dtodate, int stype)
{
List<Reportdata> reportdataobject = new List<Reportdata>();
System.Globalization.CultureInfo format = System.Globalization.CultureInfo.CurrentCulture;
var linq = (from db in Invmsobject.sp_procReports(DateTime.ParseExact(dfromdate, "MM/dd/yyyy", format), DateTime.ParseExact(dtodate, "MM/dd/yyyy", format), ((stype == 1) ? "In" : "Out").ToString())
select new Reportdata
{
ITransactionDate=db.TransactionDate.ToString(),
IProductName=db.ProductName,
ITransactionType=db.TransactionType,
IQty=db.Qty,
IUserName=db.UserName
}).ToList();
return linq;
}
Controller
public ActionResult Report()
{
return View();
}
I dont know how to assign this list values to this Report Controller.
I can assign by using this List name[ReportTransaction] but this List having Parameters that why i'm getting struck on this... I had use ajax call for passing parameters in this list.. This List working fine but i could not able to get this List datas to Controller. can anyone help me how to handle this kind of situations..
Thank you.
If this isn't what you are asking, please clarify what you are trying to do, as it is unclear.
Controller:
public ActionResult Report()
{
return View(ReportTransaction(...));
}
View:
#model List<Reportdata>
<h2>Details</h2>
#foreach(var item in Model)
{
<div>#item.IProductName</div>
}
Related
I am a new to ASP.NET MVC, I am developing an application. I want to bind the data in the drop down list in create view.
How to bind the data in the drop down? I have go through many question and answers here...
I have seen usually everyone suggested to use List<SelectListItem> what is its purpose?
Do I need to use ViewModel while binding the data to drop down list?
Can I get simple example where data get bind in the dropdown using viewbag?
I have created a list in controller
List<string> items = new List<string>();
and I want to pass this list to view using viewbag and simply want to bind to drop down list.
How to do this ?
I'd suggest using a ViewModel as it makes interaction with user input so much easier. Here's an example of how you might bind data from your ViewModel to a drop down in your View. First, the ViewModel:
public class CrowdViewModel
{
public string SelectedPerson { get; set;}
public IEnumerable<SelectListItem> People { get; set; }
}
So yes, you're right - use a collection of SelectListItems. I'm guessing in your case, the SelectListItem's Value and Text property will be the same. You could turn your List into IEnumerable like this:
[HttpGet]
public ActionResult Home()
{
// get your list of strings somehow
// ...
var viewModel = new CrowdViewModel
{
People = items.Select(x => new SelectListItem { Text = x, Value = x })
}
return View(viewModel);
}
Now you need to bind that ViewModel's property to the DropDown on your view. If you're using the Razor ViewEngine, the code will look something like this:
#model MyApp.ViewModels.CrowdViewModel
#using (Html.BeginForm())
{
#Html.DropDownListFor(model => model.SelectedPerson, Model.People)
}
Now when you post that form, MVC will bind the selected value to the ViewModel's SelectedPerson property!
[HttpPost]
public ActionResult Home(CrowdViewModel viewModel)
{
// viewModel.SelectedPerson == whatever the user selected
// ...
}
Easy as that!
Update:
If you really want to use the ViewBag (don't do it), you can pass your list through from your Controller action like so:
[HttpGet]
public ActionResult Home()
{
ViewBag.People = new List<string> { "Bob", "Harry", "John" };
return View();
}
And then create a SelectList on your View:
#Html.DropDownList("SelectedPerson", new SelectList(ViewBag.People, Model))
I am returning a List from the database. I need to return an Object for the Json method.
Any Ideas. I am new to linq and MVC.
public ActionResult Autocomplete(string term)
{
var names = itemsRepository.GetListItemNames(term);
///linq code to get my name object out
return Json(names, JsonRequestBehavior.AllowGet);
}
public ActionResult Autocomplete(string term)
{
var names = itemsRepository.GetDistinctListItemNames(term);
var getNames = names.Select(c => c.ItemName);
return Json(getNames, JsonRequestBehavior.AllowGet);
}
Since Json needed an object and I was querying a List , so this simple linq select was able to get the right object which was itemName.
I using MVC-Viewmodel in my project, my problem is that even if i CTRL-click two values in my listbox It only grabs one value. I want users to be able to select two values but I dont know why it doesnt happen any tips is appreciated!
Here is my GET n POST action inside my controller:
public ActionResult Create()
{
CreateViewModel model = new CreateViewModel();
List<CoreValue> corevalues = Arep.getallC();
model.CoreValuess = new MultiSelectList(corevalues, "CID", "Cname");
return View(model);
}
[HttpPost]
public ActionResult Create(CreateViewModel model)
{
if (ModelState.IsValid)
{
Question q = new Question();
var CoreValueID = int.Parse(model.Cname);
var getallC = Arep.getbycid(CoreValueID);
q.CoreValue.Add(getallC);
q.QuestionText = model.QuestionText;
Arep.addquestion(q);
Arep.save();
return RedirectToAction("Index");
}
return View(model);
This is inside my CreateViewModel:
public MultiSelectList CoreValues { get; set; }
And this is inside my View:
#Html.ListBoxFor(model => model.Cname,Model.Corevaluess)
What seem to be the problem?
Thanks in Advance!
Best Regards
Spelling errors aside, I believe the following is why this is failing:
In your ListBoxFor method, you are using model.Cname. By this, I believe you mean "choose the cName of selected CoreValues". However (and I'm guessing because I can't see your model), the Cname property on the CreateViewModel is of type string. Because of this, you are only ever going to have one value at a time. You need a property that is of type IEnumerable in order to hold multiple selections.
Update your model to the following:
public class CreateViewModel
{
public IEnumerable<string> SelectedValues { get; set; }
public IEnumerable<CoreValue> CoreValues { get; set; }
}
SelectedValues will be used to contain the selected values on the post. We can also add items to it to signify what should be automatically selected when the view is created.
In your controller do the following:
public ActionResult Create()
{
CreateViewModel model = new CreateViewModel();
model.CoreValues = Arep.getallC();
return View(model);
}
Lastly, update the view:
#Html.ListBoxFor(m => m.SelectedValues, new MultiSelectList(Model.CoreValues, "CID", "Cname"))
Now, whenever you post, you should be able to see the values that a user selected.
EDIT: I'm not completely sure what some of your methods do so I'm taking a guess.
The POST method for Create:
[HttpPost]
public ActionResult Create(CreateViewModel model)
{
if (ModelState.IsValid)
{
foreach(var CoreValueID in model.SelectedValues)
{
Question q = new Question();
var getallC = Arep.getbycid(CoreValueID);
q.CoreValue.Add(getallC);
q.QuestionText = model.QuestionText;
Arep.addquestion(q);
}
Arep.save();
return RedirectToAction("Index");
}
return View(model);
}
you would need to pass selectedvalues as below
List<CoreValue> selectedvalues = Null;
model.CoreValuess = new MultiSelectList(corevalues, "CID", "Cname",selectedvalues);
return View(model);
Refer MSDN link and this helpful Article
As stated above, the ASP.Net Mvc wants to have a list of string, but the same thing can be achieved by using the classic ASP style
Request.Form["CoreValues"]
this will provide as comma separated values.
In asp.net mvc3 how to keep dropdown list selected item after postback.
Do something Like this :
[HttpPost]
public ActionResult Create(FormCollection collection)
{ if (TryUpdateModel(yourmodel))
{ //your logic
return RedirectToAction("Index");
}
int selectedvalue = Convert.ToInt32(collection["selectedValue"]);
ViewData["dropdownlist"] = new SelectList(getAllEvents.ToList(), "EventID", "Name", selectedvalue);// your dropdownlist
return View();
}
And in the View:
<%: Html.DropDownListFor(model => model.ProductID, (SelectList)ViewData["dropdownlist"])%>
Even easier, you can include the name(s) of your dropdowns in your ActionResult input parameters. Your dropdowns should be in form tags. When the ActionResult is posted to, ASP.Net will iterate through querystrings, form values and cookies. As long as you include your dropdown names, the selected values will be preserved.
Here I have a form with 3 dropdowns that posts to an ActionResult. The dropdown names are (non-case sensitive): ReportName, Year, and Month.
//MAKE SURE TO ACCEPT THE VALUES FOR REPORTNAME, YEAR, AND MONTH SO THAT THEY PERSIST IN THE DROPDOWNS EVEN AFTER POST!!!!
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ReportSelection(string reportName, string year, string month)
{
PopulateFilterDrowdowns();
return View("NameOfMyView");
}
MVC does not use ViewState, which means you will need to manage the value persistence yourself. Typically this is done through your model. So, given that you have a view model, e.g.:
public class MyViewModel { }
And your controller:
public class MyController : Controller
{
public ActionResult Something()
{
return View(new MyViewModel());
}
public ActionResult Something(MyViewModel model)
{
if (!ModelState.IsValid)
return View(model);
return RedirectToAction("Index");
}
}
Now, when you pass the model back to the view with data (probably incorrect - failed validation), when you use your DropDownListFor method, just pass in the value:
#Model.DropDownListFor(m => m.Whatever, new SelectList(...))
... etc.
MVC's model binding will take care of the reading of the data into your model, you just need to ensure you pass that back to the view to show the same value again.
Assuming the selected item is part of the post, the controller now knows what it is. Simply have an entry in the ViewData dictionary indicating which item should be selected (null on get or if nothing was selected). In the view, check the value and if it's not null, select the appropriate option.
Use HttpRequestBase object.
In the view, this should work:
#Html.DropDownList("mydropdown", ViewBag.Itens as IEnumerable<SelectListItem>, new { value = Request["mydropdown"] })
If you are building the drop down list data source in the controller Action Method you can send the selected value to it
Controller:
public ActionResult Index( int serviceid=0)
{
// build the drop down list data source
List<Service> services = db.Service.ToList();
services.Insert(0, new Service() { ServiceID = 0, ServiceName = "All" });
// serviceid is the selected value you want to maintain
ViewBag.ServicesList = new SelectList(services, "ServiceID", "ServiceName",serviceid);
if (serviceid == 0)
{
//do something
}
else
{
// do another thing
}
return View();
}
View:
//ServiceList is coming from ViewBag
#Html.DropDownList("ServicesList", null, htmlAttributes: new { #class = "form-control" })
I'm passed a list of parameters. Such as "Name", "Id", "Type". There will be an many of these in url, like so:
"Name=blah1,Id=231,Type=blah1;Name=blah2,Id=2221,Type=blah1;Name=blah3,Id=45411,Type=blah3;"
I wonder if there is a way to map these query parameters to a List of objects. So, I can create an object:
MyTestObject {Name;Id;Type} and can say in my controller
Index(IList<MyTestObject> params)
params will be filled in with data from query string.
Something that is similar to http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
I actually followed advice in the article by Mr. Haack I created a class with all of the parameters as public properties. Then I had a view take a list of objects of that type. If the query parameter names follow a certain pattern (prepended by index) then I get a list of my object automatically populated and I don't have to do any manual parsing at all. This is the simplest solution for me.
Example:
query param object:
public class QueryParams
{
public string Id,
public string Name,
public string Type
}
in controller method:
public ActionResult Index(IList<QueryParams> queryData)
then I make sure that query string is formated in the following way(prepended by index):
http://localhost/myapp/?[0].id=123&[0].Name=blah&[0].Type=Person&[1].Id=345&[1].Name=example&[1].Type=Stuff
In my controller, queryData list parameter will contain two objects populated with correct data.
You can you a values provider, and it will populate values from the querystring into a single object. This is what you would do if you're not going to create a View Model.
Transform the QueryString into a FormCollection via:
var GetCollection = new FormCollection( Request.QueryString );
You could create a custom model binder, that works off the Request.QueryString collection, rather than the regular FormCollection.
E.g:
public class MyTestObjectModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var qs = controllerContext.HttpContext.Request.QueryString;
return new MyTestObject
{
Name = qs["Name"],
Id = qs["Id"],
// etc, etc
};
}
}
Then setup your [HttpGet] action accordingly:
[HttpGet]
public ActionResult Index([ModelBinder(typeof(MyTestObjectModelBinder))]MyTestObject m) {
}
You could also register it globally if you like, e.g on Application_Start() :
ModelBinders.Binders.Add(typeof(MyTestObject), new MyTestObjectModelBinder());
Then you just need the model on your action:
[HttpGet]
public ActionResult Index(MyTestObject m) {
}
Having said all of this, if you've got this many parameters, one must ask where do these parameters come from? Most likely a form on another page.
In which case, this should be a [HttpPost] action, with the parameters in the form collection, then the regular MVC model binding will take care of the above code for you.
Yes, ASP.NET MVC could automatically bind collections to action params, but you need to pass your params as a from values, moreover, it is looks like to many params you going pass in query string. Have look at this one http://weblogs.asp.net/nmarun/archive/2010/03/13/asp-net-mvc-2-model-binding-for-a-collection.aspx
Basically what you need to do:
1) Create your class which would contain your params
public class MyParam
{
public int Id {get; set;}
public string Name {get; set;}
//do all the rest
}
2) Create model which you would pass to your view
public class MyViewModel
{
IList<MyParam> MyParams {get; set;}
}
3) Create your collection in your [HttpGet] action and pass that to your view:
[HttpGet]
public virtual ActionResult Index()
{
MyViewModel model = new MyViewModel();
model.MyParams = CreateMyParamsCollection();
return View(model);
}
4) Iterate your collection in the view
#model MyViewModel
#{int index = 0;}
#foreach (MyParam detail in Model.MyParams)
{
#Html.TextBox("MyParams[" + index.ToString() + "].Id", detail.Id)
#Html.TextBox("MyParams[" + index.ToString() + "].Name", detail.Name)
index++;
}
5) Than on your [HttpPost] action you may catch your params in collection
[HttpPost]
public virtual ActionResult Index(MyViewModel model)
or
[HttpPost]
public virtual ActionResult Index(IList<MyParam> model)
P.S
Moreover, if you want to get all your form params in controller you may simple go like that:
[HttpPost]
public virtual ActionResult Index(FormCollection form)
On a related note, I was looking for a way to enumerate through the QueryString name-value collection, and this is what I came up with:
var qry =HttpContext.Request.QueryString;
if (qry.HasKeys())
{
foreach (var key in qry)
{
if(key != null)
var str= String.Format("Key:{0}, value:{1} ", key, qry.Get(key.ToString()));
}
}
This code will give you all the names and their values in the QueryString.