How to return multiple views in MVC - asp.net-mvc

I’m just wondering if I have a view with two partial views on it. How can a single controller return more than one view?
e.g.
I have a search page with a search button.
You have to option to search by Organisation or a Service.
I have created two partial views to display the results as they are different in makeup.
These partial views appear on the main Search view.
Html.Partial("_OrgResult") // partialview of results
Html.Partial("_ServiceResult") // partialview of results
I have a controller like this
[HttpPost]
public ActionResult GetResults(int SearchType = 0, string SeartchTxt = "")
{
if (SearchType < 2)
{
return PartialView("~/Views/Search/_OrgResult.cshtml", GetOrganisationResults(SearchType, SeartchTxt));
}
else
{
return PartialView("~/Views/Search/_ServicehResult.cshtml", GetServiceResults(SearchType, SeartchTxt));
}
}
is this the correct way to do this ?
Will it even work ?

The best approach would be to have a single HTML.partial line in your view:
Html.Partial("Result") // partialview of results
Then, in your controller, return the view that corresponds to the parameters:
[HttpGet]
public ActionResult Results(int SearchType = 0, string SeartchTxt = "")
{
if (SearchType < 2)
{
return PartialView("~/Views/Search/_OrgResult.cshtml", GetOrganisationResults(SearchType, SeartchTxt));
}
else
{
return PartialView("~/Views/Search/_ServicehResult.cshtml", GetServiceResults(SearchType, SeartchTxt));
}
}

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" />
}
}

MVC, cannot return to the previous URL

I am working on some legacy code.
I have a form which I edit some data and when I click save, if successful I want to return to the previous form.
So my controller methods are;
public ActionResult Edit(int callDiaryId)
{
ViewBag.PreviousUrl = System.Web.HttpContext.Current.Request.UrlReferrer;
var callDiary = this.SCDCallDiaryRepository.Get(callDiaryId);
return this.View("Edit", new DiaryItemViewModel(callDiary));
}
[HttpPost]
[ValidateAntiForgeryToken]
[ValidateOnlyIncomingValuesAttribute]
public ActionResult Edit(DiaryItemViewModel item, string previousUrl)
{
var callDiary = this.SCDCallDiaryRepository.Get(item.SCD_CallDiaryId);
callDiary.Comments = item.Comments;
callDiary.ContractId = item.ContractId;
var opStatus = this.SCDCallDiaryRepository.Update(callDiary);
if (opStatus.Status)
{
this.TempData["SuccessMessage"] = "Details updated successfully.".MessageTime();
return RedirectToAction(previousUrl);
}
this.TempData["ErrorMessage"] = "Details NOT updated.".MessageTime();
ViewBag.PreviousUrl = previousUrl;
return this.View(new DiaryItemViewModel(callDiary));
}
and the incoming value of previousUrl is
http://localhost:58384/LogDiary/Comments?companyId=11033
This works perfectly for my back button.
But after my RedirectToAction command is performed, the Bad Request error that I get is because the Url it is showing is;
http://localhost:58384/LogDiary/http%3a/localhost%3a58384/LogDiary/Comments%3fcompanyId%3d11033
How do I fix this?
I was able to do this in the Controller of my App to return the user to the previous page
public ActionResult ChangePassword()
{
var userId = this.User.Identity.GetUserId();
var viewModel = this._userService.ChangePasswordViewModelForUser(userId);
viewModel.PreviousPage = this.Request.UrlReferrer.AbsoluteUri;
return this.View(viewModel);
}
If I need to use it in a button
#Resource.Button_Cancel
I think I found the answer.
Instead of using RedirectToAction, I am now using Redirect.
You can return to the previous form by doing the below code
[HttpPost]
[ValidateAntiForgeryToken]
[ValidateOnlyIncomingValuesAttribute]
public ActionResult Edit(DiaryItemViewModel item)
{
..your other code..
return View(item);
}
it will return to the Edit page along with the entered data
hope this helps

Two partial views inside an MVC view

I have the following scenario, where I have one model (named Model A) in a view (View1).
This view initially loads a partial view (Partial View 1)
On button click of partial view, I am trying to pass the id generated to another partial view (Partial View 2).
But I am getting an error saying View 1 cannot be found, which loaded without any issues on first run.
If I remove the else statement, the page successfully reloads after submission.
Any tips on passing this model object successfully to the other view please.
I put id=1 and tested it and the same error occured.
I tried RenderAction, RenderPartial and all these failed
Page
#model MyModel
#{
if (ViewBag.Created ==0) {
#Html.Partial("CreateView1",Model);
}
else
{
{ Html.Action("Action2", "Area/Controller2", new { id = Model.Id }); }
}
}
Controller methods:
Controller 1:Entry point of view
[Route("{CreateView1}")]
public ActionResult Create() {
ViewBag.Created = 0;
return View(new MyModel());
}
[Route("{CreateView1}")]
[HttpPost]
public ActionResult Create(MyModel model) {
...........................
ViewBag.Created = 1;
}
Controller 2 which renders 2nd partial view:
public PartialViewResult Index(int createdId)
{
return PartialView(new List<Model2>());
}
Regarding View 1 cannot be found, is because the keyword return in your second Create action is missing. The button click submits the form to the Create method with [HttpPost] attribute and the end of the method, it needs a return View.
Reg Any tips on passing this model object successfully to the other view please, The return in the second Create method should be return View(model); and not 'return View(new MyModel);` as later on in the View you are going to use the Model.
Re I put id=1 and tested it and the same error occured., because runtime never reachs that point as the operation is being handed to '[HttpPost] Create' and it never get back to your Original Page.
There are other issues with your code as you are using different names in your code than what you mention in your description...
A simple solution is:
1- use the following return at the end of you [HttpPost]Create Action:
return RedirectToAction("Action2", "Area/Controller2", new { id = model.Id});
2- replace the following code in your initial page
if (ViewBag.Created ==0) {
#Html.Partial("CreateView1",Model);
}
else
{
{ Html.Action("Action2", "Area/Controller2", new { id = Model.Id }); }
}
with the following:
#Html.Partial("CreateView1",Model);
and remove anywhere you set ViewBag.Created = 0 or ViewBag.Created =1
I also assume the action action2 in controller Controller2 returns a valid Partial View.
Hope this help you get some idea to fix your code.
You may have omitted this for brevity, but you will want to return a viewresult at the end of your post action:
return View(new MyModel());
try this:
if (ViewBag.Created ==0) {
#Html.RenderPartial("CreateView1",Model);
}

While displaying data using foreach loop in MVC asp.net 4 I am not able to get the Name of the selected Item as the paramerter in Action

the code in view which i am dispalying using foreach loop
#Url.Action("StartJob", "Batch", new { batchName = #Model.BatchInformationList.ElementAt(i-1).JobName })
the code in controller
public PartialViewResult StartJob(string batchName)
{
return this.PartialView(res);
}
I am getting data in batchname of last element in the model I am iterating
Hi you can use this,
#Html.ActionLink("EditUser","StartJob", "Batch",new { batchName = #Model.BatchInformationList.ElementAt(i-1).JobName })
in ActionLink First paramete is string, second is your page likeStartJob, third is controllerBatch. And this directly redirect to your action.
Controller
public ActionResult StartJob(string batchName )
{
return this.PartialView(res);
}

Resources