Get form collection value using mvc paging - asp.net-mvc-4

How can get form collection value while paging? When i submit form then i can get form collection value. when click next page then i can not get form collection value. so what we need to change in pager?
Kindly suggest me
public ActionResult index(FormCollection fc, int? page)
{
}

Please , page id make a first and must be pass default=0
public ActionResult index( int page, FormCollection fc)
{
}

Related

.Net core Razor Pages add many child rows

How would I handle a model with many children in a razor page Create page?
I have the following models:
public class Invoice
{
public string ClientName;
public DateTime InvoiceDate;
public List<InvoiceItem> InvoiceItems;
}
public class InvoiceItem
{
public string ProductName;
public decimal Qty;
public decimal UnitPrice;
}
I want to add a button in my Invoice Create page that says "Add new item". I will then add (using ajax) a new line on the form with a new InvoiceItem - this I know how to do.
What I don't know is how to set up everything so all the invoice lines will get recognized by the OnPostAsync() method and saved in the database together with the Invoice.
Any pointers or examples would be appreciated.

How to bind dynamic complex objects created using partial-view to a collection property in view-model

I'm unable to bind a collection of child-complext objects created dynamically using a partial-view to view-model IEnumerable property.
I have successfully bound objects created dynamically using partial-views to a view-model using a technique I found on this blog https://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/. I have followed the same technique but I'm unable to bind a collection to a IEnumerable property in a view-model.
[BindRequired]
public class EmployeeViewModel
{
other properties....
public IEnumerable<ContactDetailViewModel> EmployeeContact { get; set; }
}
[BindRequired]
public class ContactDetailViewModel
{
// I use this as my indexer for dynamic elements
public string RecordId { get; set; } = Guid.NewGuid().ToString();
public string Telephone { get; set; }
public string EmailAddress { get; set; }
public string ContactDescription { get; set; }
}
I call into this action-method via ajax to add dynamic contact detail elements and it returns the partial-view as html and it works fine.
[Route("[action]", Name = "BlankEmployeeContactDetail"), HttpGet("AddBlankContactDetail")]
public PartialViewResult AddBlankContactDetail()
{
return PartialView("_ContactInformation", new ContactDetailViewModel());
}
The initial contact detail is added to the main-view using the following, kindly follow this link https://1drv.ms/u/s!AkRSHVUtFlKhuHaxH96Ik4ineATE to download the main view and partial-view cshtml files. It is also noteworthy to mention that model binding fails for all other properties when I include this partial-view but works when I comment it out. I'm baffled and would greatly appreciate any help you can afford me.
<section id="widget-grid" class="">
<div class="row contactContainer">
#{ await Html.RenderPartialAsync("_ContactInformation", new ContactDetailViewModel()); }
</div>
</section>
This is the controller action method I'm trying to bind posted data to:
[Route("[action]"), HttpPost, AllowAnonymous, ValidateAntiForgeryToken]
public IActionResult Register([FromForm] EmployeeViewModel model, [FromQuery] string returnUrl = null)
{
if (ModelState.IsValid)
{
}
return View(model);
}
In order to bind, the input names much follow a particular convention that maps to what you're binding to. While it's unclear from your question, my best guess is that you're trying to ultimately bind to an instance of EmployeeViewModel, which means that your contact information inputs would need names like: EmployeeContact[0].Telephone, but when you pass an instance of ContactDetailViewModel along as the "model" of the partial view, the names will be just Telephone, and worse, these same names will be repeated over and over, i.e. each contact information set of fields you create will all have an input named just Telephone.
Long and short, you need the context of the whole model to generate the correct input names. You have a couple of options.
Since you're retrieving the set of fields via an AJAX request, it would be possible to pass the "prefix" to use along with that request. In other words, you can keep track of an index value, counting how many of these sections you've added, and then send along with the request for a new section something like
prefix: 'EmployeeContact[' + (i + 1) + ']',
Then, in your partial view:
#{ await Html.RenderPartialAsync("_ContactInformation", new ContactDetailViewModel(), new ViewDataDictionary { TemplateInfo = new TemplateInfo { HtmlFieldPrefix = ViewBag.Prefix } } ); }
That's a little hacky, and honestly probably rather prone to error, though. The better option would be to take an entirely different approach. Instead of calling back to get the partial view, define it just once as a template:
<script type="text/html" id="ContactInformationTemplate">
<!-- HTML for contact information inputs -->
</script>
Then, using a library like Vue, React, Angular, etc., you can set up a "foreach" construction tied to a particular JavaScript array which uses this template to render items in that array. Then, adding a new set of inputs is as simple as adding a new item to the array. You will have to do some works to customize the input names based on the index of the item in the array, but all of these client-side frameworks have ways to do that. That would also have the side benefit of not having to make an AJAX request every time you want to add a new section.

RedirectToAction with model and List properties

I have a 2 views with model as Account. From view one, I am using RedirectToAction to go to view two and sending the model object as below:
[HttpPost]
public ActionResult Login(Account account)
{
//Some code here
return RedirectToAction("Index", "AccountDetail", account);
}
AccountDetail controller looks like this:
public ActionResult Index(Account account)
{
return View("ViewNameHere", account);
}
The model object contains a property like this:
public class Account
{
// Some code here
public List<Details> Details{
get;
set;
}
In the first controller, before making call to RedirectToAction there is one item in Details. However, in the Index method of second controller, there is nothing.
Can someone help pointing out the flaw here? Since I am beginner with MVC, cannot seem to figure it out.
You should not pass a complex object to a GET method. Apart from the ugly URL it would create, you could easily exceed the query string limit and throw an exception.
In any case you cannot pass a collection (or a complex object containing a collection) to a GET method using RedirectToAction(). Internally the method uses reflection to generate the query string by calling the .ToString() method of each property of the model, which in the case of your collection property will be something like ../AccountDetail/Index?Details=System.Collections.Generic.List<Details>.
When the Index() method is called, a new instance of Account is initialized and the value of its property Details is attempted to be set to the string System.Collections.Generic.List<Details> which fails and the result is that property Details is null.
Options include passing an identifier and get the collection from the repository or Session or TempData

Change ViewModel default data strictly from server in MVC?

I know this is a weird one but bear with me. I need to set a default state/value for form inputs on a portion of my application.
In my "MainController" I pull up a portion (or 'wrapper' of sorts) page and then pull partial views from this main page. Here's a pseudo-code example:
User goes to Main ->
MainController/Index Called
-> User clicks Link A ->
AJAX .load() pulls html from PartialViewA into #partialContainer
-> User clicks Link B ->
AJAX .load pulls html from PartialViewB into #partialContainer
Here's the AJAX call:
$("#mainPanel").load('#Url.Action("GetModule","Settings")' + '?partialName=' + moduleName);
...and the corresponding server-side action that handles it:
public ActionResult GetModule(string partialName)
{
return PartialView(partialName);
}
It works great for me, each of the modules has plenty of form fields on them, all interacting well with one another and server so that isn't my problem. The issue is setting default values from the dbase for the form fields contained in the partial views.
For instance the "General" partial has many checkboxes which will determine how portions of the application display. I want to pull from the database the pre-exisiting boolean value and when the partial gets pulled from GetModule(), have these values defaulted.
I've taken a look around and I'm afraid the way that I am pulling the partial's into the main page may be the issue. I thought I could build the defaults into the constructor like so:
public class GeneralViewModel
{
public GeneralViewModel()
{
var Data = from m in dataContext.Table
where m.UserID == _id
select new
{
m.Data1,
m.Data2,
};
foreach(var setting in Data)
{
Checkbox1 = Convert.ToBoolean(setting.Data1); // Conversion from bool? to bool
Checkbox2 = Convert.ToBoolean(setting.Data2); // Conversion from bool? to bool
}
}
public bool Checkbox1 { get; set; }
public bool Checkbox2 { get; set; }
}
But it would appear the constructor never gets called. That sort of makes sense, except when you consider the fact that my form fields are not only rendering properly, but communicating with the database just fine as well. So the question is, what am I doing wrong? Is it the way I call the Partial's or am I missing something with assigning values to my VM values?
As always, thanks SO!
I think it's better to have different action methods for rendering the partial views, but for your case, i think this solution would work.
Have a Model that contains the other view models
public class ViewModel
{
public ViewModel1 ViewModel1 { get;set;}
public GenereViewModel General {get;set;}
}
Then in your controller you could initialize the viewmodel based on the partial name.
public ActionResult GetModule(string partialName)
{
var model = new ViewModel();
switch (partialName)
{
case "General": model.General = InitializeGeneral();
break;
case "ViewModel1": model.ViewModel1 = InitializeViewModel1(); break;
}
return PartialView(partialName, model);
}
private GeneralViewModel InitializeGeneral()
{
// initalize then return model
}

Same view for both create and edit in MVC4

Can we have a single razor view for both Create and Edit operations?
If yes, how do we achieve this?
I don't recommend it.
This should be a rather long answer, because there's a lot of things involved in the process, request and workflow of a normal MVC GET/POST workflow. I will try to answer your question with the minimum information required and why I do not recommend the use of the same view.
First, why?
You don't have control over the views, which may have over-posting;
No flexibility;
Not reusable views or parts;
Hard to maintain the views (one change in the view must be tested on both actions).
My suggested approach would be to have different actions/views but share common code:
Create both views as normal.
You will have duplicated code, but not all code is the same, for example, you may not want to send an ID on the create action, this is not directly related to your question, but using the same view implies you are also sending the same data, and this is not recommended, especially for over-posting or mass assignment. More info about mass assignment here (an Architectural Approach is what I'm using here).
So let's start from what are you going to receive in your controllers.
In this case I used inheritance but it's not the only strategy.
Binding models
public class UpdateBindingModel : CreateBindingModel {
// since we are not using the same binding model,
// we can have a "real" validation rules on our update binding and view.
[Required]
public int? Id {get;set;}
}
public class CreateBindingModel {
// no id here prevent overposting.
[Required]
public string Name {get;set;}
[Required]
public int? CountryId {get;set;}
}
That will make sure the data you send to your Create and Edit is the minimum needed and nothing else.
Let's then see the View Models that will be sent to the View, for this example I will include a List that will be used to select some value but should not be posted (the list) to the controller, only the selected value.
View models
public class CreateViewModel : CreateBindingModel {
public IEnumerable<SelectListItem> CountryList {get;set;}
}
public class UpdateViewModel : UpdateBindingModel {
public IEnumerable<SelectListItem> CountryList {get;set;}
}
As you can see, this gives you lot of flexibility but still have some duplicated code (the extra information needed on view model for both views) which can be mitigated in several ways (depending the needs/context):
Have an action to retrieve the common data and using #Html.Action("GetCountryList");
Use the same View Model aka CreateUpdateViewModel and discarding extra UpdateBindingModel properties in the view but still posting the corresponding model on POST.
Having your binding models as properties and select one or the other in the specific view. (better use #Html.EditorFor instead of partials so Model Binder will work with no additional change on code)
The controller actions will look like:
Controller
[HttpGet]
public ActionResult Create(){
ViewData.Model = new CreateViewModel();
return View();
}
[HttpPost]
public RedirectToRouteResult Create(CreateBindingModel binding) {
// check valid model state and create data
return RedirectToAction("Index");
}
[HttpGet]
public ActionResult Update(int id) {
var objectToEdit = service.GetObjectToEdit(id);
ViewData.Model = new UpdateViewModel(objectToEdit);
return View();
}
[HttpPost]
public RedirectToRouteResult Update(UpdateBindingModel binding) {
// check valid model state and update data
return RedirectToAction("Index");
}
And your views:
Views
Update.cshtml
<form action="Update">
#Html.HiddenFor(Model.Id);
#Html.Partial("EditFieldsPartial")
<button>delete</button> // no delete button on create.
<button>create new</button> // you can have a create new instead of update.
</form>
Create.cshtml
<form action="Create">
#Html.Partial("EditFieldsPartial")
</form>
Note: code is incomplete and didn't use helpers in most cases for brevity and clarity. Do NOT copy paste :D
Sure you can.
On post, check in your controller whether the primary key has value 0 then Insert, otherwise Update.
View should be the same for Create and Edit.
Just remember to include:
#Html.HiddenFor(model=>model.ID)
In your view
For example:
Model:
public class DescriptionModel
{
[Key]
public int ID { get; set; }
public string Description { get; set; }
}
CreateEdit.cshtml:
#model DescriptionModel
#using (Html.BeginForm("CreateEdit"))
{
#Html.HiddenFor(model=> model.ID)
#Html.EditorFor(model=> model.Description)
<input type="submit" value='Submit' />
}
DescriptionModel controller:
public ActionResult Create()
{
return View("CreateEdit", new DescriptionModel());
}
public ActionResult Edit(int id)
{
return View("CreateEdit", db.DescriptionModels.Find(id));
}
// Submit and add or update database
[HttpPost]
public ActionResult CreateEdit(DescriptionModel model)
{
if (ModelState.IsValid)
{
// No id so we add it to database
if (model.ID <= 0)
{
db.DescriptionModels.Add(model);
}
// Has Id, therefore it's in database so we update
else
{
db.Entry(model).State = EntityState.Modified;
}
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
A View can definitely be shared for create and edit operations, using the same model. However, i would strongly recommend to think about it twice. In many cases, you will want to have a different view for edit operations(eg. hide some inputs that should not be editible) as well as the model could be slightly different, altought it might share some (or most) values. These difference will lead to some conditions in the view, checking whether you are creating or editing - which could make the code chaotic.
Conclusion: before deciding whether to have a shared view, try to think of how much is the edit screen gonna differ from create screen, then you may decide.
You certainly can, but usually that's something I will try to avoid. If the create and edit actions are virtually the same then you end up duplicating a lot of code in the controller. Usually in this situation I will have only a few fields on my 'Add' controller, and then once the item has been added I redirect the user to the edit page where they can fill in the rest of the information.
I wouldn't recommend that approach but you could have the main form be loaded into both views from a partial
[HttpGet]
public ActionResult myFun(int id = 0)
{
MyClass cls = new MyClass();
if (id == 0)
{
//Insert mode ... no data will be shown to textboxes , when primary key ie. id=0
//Display whole data
}
else
{
//Update mode... if id is not 0 ,data will be shown to textboxes
}
return View(cls);
}