MVC4 two controllers with a common partial view issue - asp.net

From the image i try to load two controllers, on pageload Browse controller loads with 1 and 2 data from picture, when i want to select the date,it should load the dayselect controller data in same page. How can i do this , My controllers are here
public ViewResult Browse(Int32 eventid) {
//code
return view(ef);
}
public ActionResult DaySelect(EventModel m) {
return view("_Common",k);
}
My viewModel for Browse Controller is Browse.cshtml
#model BrowseEventModel
<div class="Event_Name" id="id_name">#Model.EventName</div>
<div class="Event_loc" id="id_loc">#Model.EventLocation</div>
//In this view i have a widget which i load in partial view
<div class="yui3-g" id="bottom_container"> #{Html.RenderPartial("_Common");}
</div>
The partial view is _common.cshtml
#model BrowseEventModel
<select name="dayNo" id="dayNo">
#foreach (var s in Model.Dayselector) {
<option value = "#s.DayNo"> #s.DayDate.ToString("dd MMM yyyy")</option>
}
</select>
//View Model used for both browse and dayselect controller
#foreach(var e in Model.DisplayData){
<ul id="ul-data">#e.dataName</ul>
<div id="ul-id">#e.dataid</div>
}
When i select the date it should load data in same view page is it possible,i.e injecting view on runtime

You can use AJAX to inject view at runtime. In your case, you are depending on the onchange event of a DropDownList. A question has already been asked with the same problem as yours. Try this: using ajax with dropdownlist mvc3

Related

Building ASP.NET with MVC, trying to create a filter from Dropdown list

First post here so be gentle please :)
I am creating an ASP.NET with MVC web app that shows a list of items of the same class (Laptop)
I want to create a Dropdown list in the main view below each title that will allow me to filter the results OnChange - hence the selection is empty, but the user can click and select the value in the DropDown list, and the main view items list will update immediately according to the selection.
This is how the list looks now:
Snapshot of the list
I want to implement a dropdown, but I can't seem to get the selected value from the dropdown: (The DropDownlist is populated properly, and working)
<select class="form-control" asp-items="Html.GetEnumSelectList<purpose>()"
onchange="#{Model = Model.Where(m=>m.Purpose == /*HERE SHOULD BE THE VALUE SELECTED*/)}">
<option selected="selected" value="">-Select one-</option>
</select>
And then refreshing the page... but - how do I get the selected value from inside the selection?
If it was in JavaScript I would have done:
html.document.getElementById("The id of the selection").value
but I don't want JavaScript since this is all ASP.NET
To be clear, I have 5 different dropdown lists to filter by, and they can be selected or not.
You're mixing up client-side vs. server-side code. The example below uses only MVC and a full client-server architecture. Each request requires a round-trip to the server.
You have 3 components in this scenario.
ProductsViewModel.cs
public class ProductsViewModel
{
public IList<Laptop> Laptops { get; set; }
public PurposeEnum Purpose { get; set; }
}
ProductsController.cs
public class ProductsController : Controller
{
[HttpGet]
public IActionResult Index()
{
// Retrieve all records without a filter
var unfiltered = db.Laptops.ToList();
var viewModel = new ProductsViewModel() { AvailableLaptops = unfiltered };
return View(viewModel);
}
[HttpPost]
public IActionResult Index(ProductsViewModel viewModel)
{
// Use viewModel.Purpose & viewModel.Maker to filter records from database
var filtered = db.Laptops.Where(l => l.Purpose == viewModel.Purpose).ToList();
var filteredViewModel = new ProductsViewModel()
{
AvailableLaptops = filtered,
Purpose = viewModel.Purpose
};
return filteredViewModel;
}
}
Products\Index.cshtml
#model MyNameSpace.ViewModel
using (BeginForm())
{
#Html.DropDownList(Html.GetEnumSelectList<PurposeEnum>())
foreach (var l in Model.AvailableLaptops)
{
// Loop through Model.AvailableLaptops and generate table
}
<input type="submit" value="Search" />
}
When you visit the URL /Products/Index for the first time, the GET action handler will be triggered. It will generate an unfiltered list of your products along with the dropdown list required for filtering.
When you make your selection and submit the form, the POST action handler will be triggered, and use the selected values in the Purpose and Maker properties of the view model to filter the records. The same view is generated, but with a filtered down list of products.
This is very basic code that ignores validation, error handling and security.

How to get the user entered data from view to controller and then insert into database, in MVC?

I am a beginner and currently started a small project for my study purpose. A mini DB search portal. I created front end View. It has one search box and a button. Now what I need is, I have to fetch the data from DB, related to the user entered search term on clicking on the button.
How to proceed to get the user entered data from view to controller and process it for further operations.
General code:
view:
#using(Html.BeginForm("Search","Test"))
{
<input type="text" name="txtName"/>
<input type="submit" value="Generate report" />
}
Controller
[HTTPPost]
public ActionResult Seacrh(FormCollection form) // "Search" is action name specified in view for controller "TestController"
{
string text = form["txtName"]; // txtName is name of input in view.
}
However to take full advantage to MVC have a look at Model Binding in MVC
I recommend reading this article, it has an example different ways of adding search.
You can update the Index method in your Controller and View as follows:
1)Add a form to the view that will post to the view itself
View
#using (Html.BeginForm()){
<p> Title: #Html.TextBox("SearchString") <br />
<input type="submit" value="Filter" /></p>
}
2)Add a parameter to the Index method to filter the content based on the parameter passed. public ActionResult Index(string searchString)
Controller
var movies = from m in db.Movies
select m;
if (!String.IsNullOrEmpty(searchString))
{
movies = movies.Where(s => s.Title.Contains(searchString));
}
return View(movies);

Getting values of check-box from formcollection in asp.net mvc

I viewed some topics here but I still have a problem with getting values from checkboxes.
Part of Model :
public Dictionary<Language, bool> TargetLanguages { get; set; }
Part of View :
<div class="editor-label">
<label for="TargetLanguages">select target languages</label>
</div>
<div class="editor-field">
<form>
#foreach (var item in Model.TargetLanguages)
{
#Html.CheckBox("TargetLanguages["+item.Key.Name+"]", item.Value)
#item.Key.Name
}
</form>
</div>
Part of Controller :
[HttpPost, ActionName("AddDictionary")]
public ActionResult AddDictionary(FormCollection collection)
{
...
}
And the problem is I don't get any trace of TargetLanguages in my FormCollection. I tried CheckBoxFor but it wasn't help. I tried write check-box manually also.
EDITED : Okay, I just noticed where the problem was. I've got messed up markers and that was the reason why I can't get data from FormCollection.
Create all the checkboxes with the same name. In this sample I'm using 'SelectedTargetLanguages'.
#using (Html.BeginForm())
{
foreach (var item in Model.TargetLanguages)
{
<label>
#Html.CheckBoxFor(m => m.SelectedTargetLanguages, item.value)
#item.KeyName
</label>
}
<br/>
#Html.SubmitButton("Actualizar listado")
}
Then, in your action the parameter must be an array of strings like this:
public ActionResult AddDictionary(string[] selectedTargetLanguages)
Note that the name of the argument is the same name of the checkboxes. (It works even with the different casing).
You should use explicit arguments like this, rather than the generic FormCollection. Anyway, if you use FormCollection, you shpuld also receive the array.
I have asked same type of question previously. Please check the following links
MVC3 #Html.RadioButtonfor Pass data from view to controller
MVC3 #html.radiobuttonfor
I think this might helps you.

Asp.net MVC cancel button with multiple redirect choices

I currently have a form with a submit and cancel button. Depending on some logic, each time the page loads, I want that same cancel button to redirect to different other pages in the application. This is the code I have at the moment in my aspx view that changes the location.href based on my property
<% if (Model.MyProperty.Equals("something"))
{ %>
<input class="btnCancel" type="button" value="" onclick="location.href='<%: Url.Action("MyAction","MyController", new {Area="MyArea"},null)%>'" />
<% } %>
<% else if (Model.MyProperty.Equals("somethingelse"))
{ %>
<input class="btnCancel" type="button" value="" onclick="location.href='<%: Url.Action("MyOtherAction","MyOtherController", new {Area="SomeOtherArea"},null)%>'" />
<% } %>
Is this the correct and elegant way to do this? I would rather reduce the multiple IF-ELSE conditions if there was a way to do it.
Thanks for your time.
The way I've always handled multiple redirect options is by setting the href value in the controller action.
The View is generic, but the controller action is specific to the context of the page your rendering. So in your model, make a property called CancelUrl. Now, in the controller action, set it to the link you want it to go to.
model.CancelUrl = Url.Action("action", "controller");
This way, all you have to do in your View is say
Text
You can create a cancel method that takes your property as a parameter and redirect appropriately within the controller. This logic should probably not be in your view anyway as views should have almost 0 logic anyway
I would put the property that will be used to decide the cancel action in the view model (as you already have), alongside any other required properties.
For example:
public class IndexModel
{
//any other properties you need to define here
public string MyProperty { get; set; }
}
Then your view would look similar to:
#model IndexModel
#using (Html.BeginForm())
{
//other information you may want to submit would go here and in the model.
#Html.HiddenFor(m => m.MyProperty)
<button type="submit" name="submit" value="submit">submit</button>
<button type="submit" name="cancel" value="cancel">cancel</button>
}
And finally, your post action should decide the next action that should be returned:
[HttpPost]
public ActionResult Index(IndexModel model)
{
if (!string.IsNullOrEmpty(Request["submit"]))
{
if (ModelState.IsValid)
{
//any processing of the model here
return RedirectToAction("TheNextAction");
}
return View();
}
if (model.MyProperty.Equals("something"))
{
return RedirectToAction("MyAction", "MyController", new { area = "MyArea" });
}
else //assumes the only other option is "somethingelse"
{
return RedirectToAction("MyOtherAction", "MyOtherController", new { area = "SomeOtherArea" });
}
}

Create controller for partial view in ASP.NET MVC

How can I create an individual controller and model for a partial view? I want to be able to place this partial view any where on the site so it needs it's own controller. I am current rendering the partial as so
#Html.Partial("_Testimonials")
Why not use Html.RenderAction()?
Then you could put the following into any controller (even creating a new controller for it):
[ChildActionOnly]
public ActionResult MyActionThatGeneratesAPartial(string parameter1)
{
var model = repository.GetThingByParameter(parameter1);
var partialViewModel = new PartialViewModel(model);
return PartialView(partialViewModel);
}
Then you could create a new partial view and have your PartialViewModel be what it inherits from.
For Razor, the code block in the view would look like this:
#{ Html.RenderAction("Index", "Home"); }
For the WebFormsViewEngine, it would look like this:
<% Html.RenderAction("Index", "Home"); %>
It does not need its own controller. You can use
#Html.Partial("../ControllerName/_Testimonials.cshtml")
This allows you to render the partial from any page. Just make sure the relative path is correct.
If it were me, I would simply create a new Controller with a Single Action and then use RenderAction in place of Partial:
// Assuming the controller is named NewController
#{Html.RenderAction("ActionName",
"New",
new { routeValueOne = "SomeValue" });
}
The most important thing is, the action created must return partial view, see below.
public ActionResult _YourPartialViewSection()
{
return PartialView();
}
You don't need a controller and when using .Net 5 (MVC 6) you can render the partial view async
#await Html.PartialAsync("_LoginPartial")
or
#{await Html.RenderPartialAsync("PartialName");}
or if you are using .net core 2.1 > you can just use:
<partial name="Shared/_ProductPartial.cshtml"
for="Product" />
Html.Action is a poorly designed technology.
Because in your page Controller you can't receive the results of computation in your Partial Controller. Data flow is only Page Controller => Partial Controller.
To be closer to WebForm UserControl (*.ascx) you need to:
Create a page Model and a Partial Model
Place your Partial Model as a property in your page Model
In page's View use Html.EditorFor(m => m.MyPartialModel)
Create an appropriate Partial View
Create a class very similar to that Child Action Controller described here in answers many times. But it will be just a class (inherited from Object rather than from Controller). Let's name it as MyControllerPartial. MyControllerPartial will know only about Partial Model.
Use your MyControllerPartial in your page controller. Pass model.MyPartialModel to MyControllerPartial
Take care about proper prefix in your MyControllerPartial. Fox example: ModelState.AddError("MyPartialModel." + "SomeFieldName", "Error")
In MyControllerPartial you can make validation and implement other logics related to this Partial Model
In this situation you can use it like:
public class MyController : Controller
{
....
public MyController()
{
MyChildController = new MyControllerPartial(this.ViewData);
}
[HttpPost]
public ActionResult Index(MyPageViewModel model)
{
...
int childResult = MyChildController.ProcessSomething(model.MyPartialModel);
...
}
}
P.S.
In step 3 you can use Html.Partial("PartialViewName", Model.MyPartialModel, <clone_ViewData_with_prefix_MyPartialModel>). For more details see ASP.NET MVC partial views: input name prefixes

Resources