I create my partial view with #Html.Action() like so:
#Html.Action("Index", "AreaMenu", new { Area = "" })
In the partial view's controller I'd like to get the browser querystring, unfortunately if I try to get it from System.Web.HttpContext.Current.Request.Url.AbsolutePath I get url to the controller not what's in the address bar.
How do I get this?
#inherits System.Web.Mvc.WebViewPage
#using System.Web.Mvc.Html;
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script>
var location = window.location;
</script>
<div class="row">
#Html.Action("Index", "AreaMenu", new { Area = "" })
<!--Start Content-->
<div id="content" class="col-xs-12 col-sm-10">
<div id="ajax-content">
<!--Start Breadcrumb-->
<div class="row">
<div id="breadcrumb" class="col-xs-12">
<ol class="breadcrumb pull-left">
<li>
<a href='#Url.Action("Index", "Home", new { area = "" })'>
<i class="fa fa-home"> </i> Nuclei
</a>
</li>
<li>
<a href='#Url.Action("Index", "Home", new { area = (string)ViewBag.AreaName })'>#ViewBag.CurrentModule.Name</a>
</li>
<li>
<a href=''>#ViewBag.AreaView</a>
</li>
</ol>
</div>
</div>
<!--End Breadcrumb-->
#RenderBody()
</div>
</div>
<!--End Content-->
</div>
MVC treats this as a standalone request (as if you are entering this action in the address bar). That is why are seeing the controller in the AbsolutePath and not what is in the address bar.
You could pass the querystring as a parameter in your Action.
see: https://stackoverflow.com/a/14152825/893543
OR
Couldn't the model you use to generate the page contain everything you need? The query string is what was passed to the controller that made the page, just add the properties you need to the model?
Related
I have designed a page using html tags. i have used the same code in a View in my MVC application. The page has three tabs tab1, tab2 and tab3.
#using (Html.BeginForm("ViewName", "Home", FormMethod.Post))
{
<div class="col">
<ul class="nav nav-tabs" id="myTab" role="tablist">
<li class="nav-item">
<a class="nav-link active" id="tab">Search</a>
</li>
<li class="nav-item">
<a class="nav-link tab" id="tab2" href="#tab2"</a>
</li>
<li class="nav-item">
<a class="nav-link tab" id="tab3">Details</a>
</li>
</ul>
</div>
<div class="col-auto text-right">
#Html.TextBoxFor(Model => Model.Name) <!--This is my text box to enter the text.-->
<input type="submit" class="btn btn-primary" value="Search" name="Search" action="ViewName"><!--On submitting it, it will hit the "test" action method in the Controller.-->
</div>
<div class="tab-pane fade" id="tab2" role="tabpanel" aria-labelledby="results-tab">
<table id="Table" class="table" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Name1</th>
</tr>
</thead>
<tbody>
<tr>
<td>name2</td>
<td>name2</td>
</tr>
</tbody>
</table>
</div>
<div class="tab-pane fade" id="details" role="tabpanel" aria-labelledby="details-tab">Details</div>-- the above is the table to which i want to bind the data and show the result and it is in the same view.
}
The above is the HTML code i am using in my view of the MVC code. i have three tabs in my Html code.
In my Tab1:
I have a text box with my search button.
I am binding the text box to the required model property.
After i have entered the text and hit the search button. It would call an API and give the list which contains or equals the required text.In my controller i have used the [HttpPost] attribute.I am posting the form on clicking the submit button.
public IActionResult ViewName()
{
NameModel obj = new NameModel();
return View("ViewName", obj);
}
[HttpPost]
public IActionResult ViewName(NameModel obj1)
{
NameModel model = new NameModel();
-- Call the api and take out the Json response.
--Bind the json response to the Model.
--Send the model back to the same view but different tab.
return View("ViewName", model);
}
Now i want to display the result in the Tab2 in the grid format which is in the Same View.
The tab2 contains the table. How do i bind the resulted model value to it since it is in the same view.
I dont want to use the JQuery. i want to use any .net core concepts to implement it.
Can someone please tell me how to do it.
Solution 1: Partial view included in different views
I would go for another type of implementation. It looks like the views are indeed different from each other and the fact that you require different models for each tab tells me the same.
If that's the case, Check the partial view guide here
The main idea is to create the navbar as a reusable partial view, and include it in every other View (that is every other tab) you want to use.
Solution 2: Use the jquery option
MVC uses html/css and javascript to render clientside items. It is not non-MVC practice to use JQuery with it, it is in fact a common practice.
Solution 3: Use razor logic check w3schools entry
You can add checks like this below in your razor and have one model
#if (Model.Tab == 1)
{
<div class="col-auto text-right">
#Html.TextBoxFor(Model => Model.Name) <!--This is my text box to enter the text.-->
<input type="submit" class="btn btn-primary" value="Search" name="Search"
action="ViewName"><!--On submitting it, it will hit the "test" action method in the
Controller.-->
}
</div>
Now in your backend, change the Model.Tab and have an overall model like this:
public MyModel {
public int Tab;
public TabOneModel;
public TabTwoModel;
public TabThreeModel;
}
While I have seen this quite a lot it has major disadvantages.
You can't apply an overall validation.
Your code will become very complicated in a single function. It violates multiple principles and can't be easiy unit tested.
IMO, you could post the name using ajax and return the partial view where locates the Tab2 content, and display the result to the main view.
Refer to my following steps:
1.ViewName.cshtml
#model NameModel
<div class="col">
<ul class="nav nav-tabs" id="myTab" role="tablist">
<li class="nav-item">
<a class="nav-link active" href="#tab" role="tab" data-toggle="tab">Search</a>
</li>
<li class="nav-item">
<a class="nav-link tab" href="#tab2" role="tab" data-toggle="tab">Grid</a>
</li>
<li class="nav-item">
<a class="nav-link tab" href="#tab3" role="tab" data-toggle="tab">Details</a>
</li>
</ul>
</div>
<div class="tab-content">
<div role="tabpanel" class="tab-pane fade in active" id="tab">
<div class="col-auto text-right">
<input asp-for="#Model.Name" id="myText" />
<input type="button" class="btn btn-primary" onclick="myFunction()" value="Search" id="Search" name="Search" /><!--On submitting it, it will hit the "test" action method in the Controller.-->
</div>
</div>
<div role="tabpanel" class="tab-pane fade" id="tab2">
<div id="Tab2Content">
</div>
</div>
<div role="tabpanel" class="tab-pane fade" id="tab3">ccc</div>
</div>
#section Scripts{
<script>
function myFunction() {
var name = document.getElementById("myText").value;
$.ajax({
type: 'POST',
url: '/Home/ViewName',
data: { name: name },
error: function (result) {
console.log("error");
},
success: function (result) {
$("#Tab2Content").html(result);
}
});
}
</script>
}
2.Post method:
[HttpPost]
public IActionResult ViewName(NameModel obj1)
{
NameModel model = new NameModel();
-- Call the api and take out the Json response.
--Bind the json response to the Model.
--Send the model back to the same view but different tab.
return PartialView("_Tab2PartialView", tab2model);
}
3.Partial View (located at /Views/Shared/_Tab2PartialView.cshtml) to display the grid
#model tab2model
#*or #model List<tab2model>*#
#*grid view*#
<table id="Table" class="table" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Name1</th>
</tr>
</thead>
<tbody>
<tr>
<td>name2</td>
<td>name2</td>
</tr>
</tbody>
</table>
In my view I have the following which is my home page:
#Html.ActionLink("OVERVIEW", "List", "Items", null, new { #class = "navItem" })
I have a logo, which I want make it click able and once clicked direct me to home page(the one above),the following does not work,any suggestion?:
<div class="nav-primary">
<a #{Response.Redirect("OVERVIEW"); } > <img src="#Url.Content("~/Content/Images/theLogo.png")" /></a>
</div>
Try,
<div class="nav-primary">
<img src="#Url.Content("~/Content/Images/theLogo.png")" />
</div>
I am new to the world of MVC programming with C #, I already read the topic, made some examples and of course with the guide of StackOverflow I think I'm doing well.
However I find myself with an exercise that I want to perform and from which I have seen several answers but none has worked for me, and I come to you asking for the support.
Index
#{
ViewBag.Title = "Bienvenido";
}
<div class="container-fluid">
<div class="row">
<div class="col-md-3" id="menu">
<ul class="nav nav-pills nav-stacked">
<li role="presentation" class="active">Inicio</li>
<li role="presentation">Datos Generales</li>
<li role="presentation">Datos Curriculares</li>
<li role="presentation">Experiencia Laboral</li>
<li role="presentation">Datos Laborales</li>
<li role="presentation">Cónyuge y Dependientes</li>
<li role="presentation">Inmuebles</li>
<li role="presentation">Vehículos</li>
<li role="presentation">Muebles</li>
<li role="presentation">Inversiones</li>
<li role="presentation">Adeudos</li>
<li role="presentation">Posible Conflicto de Intereses</li>
<li role="presentation">Observaciones</li>
</ul>
</div>
<div class="col-md-9">
<div class="row" id="opciones">
</div>
<div class="row" id="crear">
</div>
<div class="row" id="registros">
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
$('#dependientes').click(function () {
$.get('#Url.Action("Create","Dependientes")', function (data) {
$('#crear').replaceWith(data);
});
});
});
$(function () {
$('#dependientes').click(function () {
$.get('#Url.Action("Mostrar","Dependientes")', function (data) {
$('#registros').replaceWith(data);
});
});
});
</script>
Partial View _Mostrar
#model List<projectD.Models.dependiente>
#{
ViewBag.Title = "_Mostrar";
}
<br />
<div class="container">
<div class="row">
#foreach (var item in Model)
{
<div class="card" style="width: 20rem; display:inline-block; margin-top:10px">
<img class="card-img-top" src="~/Content/images/familia.png" alt="Card image cap" width="50" height="50">
<div class="card-block">
<h4 class="card-title">Dependiente</h4>
<p class="card-text">
#item.nombre
<br />
#item.apellidoPaterno
<br />
#item.apellidoMaterno
<br />
#item.CURP
</p>
#Html.ActionLink("Detalle", "Details", new { id = item.idDependiente }, new {#class= "btn btn-primary"})
</div>
</div>
}
</div>
</div>
I have a project with a main view, which has a menu to the left when selecting each option to the right render two partial views each with its controller the first to add records and the second to display them.
main screen
What I want to do is that when I click on add record, only the partial views are updated and the URL is not reloaded since I would lose the menu option in which I am.
I hope you can support me
I have two partial views which need to be loaded when their respective tab is selected. I am unable to get the tabs to change and it always shows the same partial view.
I tried to base my code on this answer https://stackoverflow.com/a/22483758/4761773
Here is my code :
<div>
<ul class="nav nav-tabs">
<li>#Html.ActionLink("Organization Users", "Index", new { allUsers = 0 }, new { id = "OrgUsers" })</li>
<li>#Html.ActionLink("All Users", "Index", new { allUsers = 1 }, new { id = "AllUsers" }) </li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="OrgUsers">
#Html.Partial("_ListUsers")
</div>
<div class="tab-pane" id="AllUsers">
#Html.Partial("_ListAllUsers")
</div>
</div>
</div>
Am I missing some thing?
I do not see any condition of how you can differenciate between the _ListUsers and _ListAllUsers. Maybe you can have an if condition with one partial loading for one condition and another partial for the other.
<div class="tab-content">
#if (some condition)
{
<div class="tab-pane active" id="OrgUsers">
#Html.Partial("_ListUsers")
</div>
}
else if (condition 2)
{
<div class="tab-pane active" id="AllUsers">
#Html.Partial("_ListAllUsers")
</div>
}
</div>
I am new as MVC 5, I have create a new project and I am setting up the login (With external login).
This is using the VIsual Studio 2013 MVC 5 Application template
So what is happening is when I click the button for a social media login I am getting an error of the wrong model being passed
The model item passed into the dictionary is of type
'WebPortal.Models.LoginViewModel', but this dictionary requires a
model item of type 'WebPortal.Models.ExternalLoginListViewModel'.
If you need the controls and model code let me know. But as I said this is the default code that came with the template. The only things I have been changing is the View at this point to change the look. And have posted the View Code below.
I think the issue is that since I am starting from the Layout page, the model is never being initiated since there is no model for the layout.... Again I am new so I am only guessing.
Here is the Partial path
"_Layout" -> "_SocialBar"(Partial View) -> "Login"(Partial View) -> "LoginPartial"(Partial View) -> "_ExternalLoginsList"(Partial View)
SocialBar (Partial View)
<div class="header-top dark ">
<div class="container">
<div class="row">
<div class="col-xs-3 col-sm-6 col-md-9">
...Some Code....
<!-- header-top-first end -->
</div>
<div class="col-xs-9 col-sm-6 col-md-3">
#Html.Partial("_Login")
</div>
</div>
</div>
</div>
Login Partial View page
#using Microsoft.AspNet.Identity
#if (Request.IsAuthenticated)
{
...Some Code...
}
else
{
...Some Code...
#Html.Partial("_LoginPartial")
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
LoginPartial View Code
#using WebPortal.Models
#model LoginViewModel
#using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { role = "form" }))
{
#Html.AntiForgeryToken()
<form class="login-form margin-clear">
<div class="form-group has-feedback">
<label class="control-label">#Html.LabelFor(m => m.Email)</label>
#Html.TextBoxFor(m => m.Email, new { #class = "form-control" })
<i class="fa fa-user form-control-feedback"></i>
</div>
<div class="form-group has-feedback">
<label class="control-label">#Html.LabelFor(m => m.Password)</label>
#Html.PasswordFor(m => m.Password, new { #class = "form-control" })
<i class="fa fa-lock form-control-feedback"></i>
</div>
<div class="form-group has-feedback">
#Html.CheckBoxFor(m => m.RememberMe)
<label class="control-label">#Html.LabelFor(m => m.RememberMe)</label>
</div>
<input type="submit" value="Log in" class="btn btn-gray btn-sm" />
<span class="pl-5 pr-5">or</span>
#Html.ActionLink("Sign Up", "Register", "Account", null, new { #class = "btn btn-default btn-sm" })
<div class="form-group has-feedback">
Forgot your password?
</div>
#Html.Partial("../Account/_ExternalLoginsList")
</form>
}
ExternalLogin List Code
#model WebPortal.Models.ExternalLoginListViewModel
#using Microsoft.Owin.Security
#{
var loginProviders = Context.GetOwinContext().Authentication.GetExternalAuthenticationTypes();
if (loginProviders.Count() == 0)
{
<span class="text-center">No External Logins</span>
}
else
{
<span>Login with   
#foreach (AuthenticationDescription p in loginProviders)
{
switch (#p.AuthenticationType)
{
case "Facebook":
<button type="submit" class="btn btn-xsm facebook" id="#p.AuthenticationType" name="provider" value="#p.AuthenticationType"><i class="fa fa-facebook"></i></button>
break;
case "Twitter":
<button type="submit" class="btn btn-xsm twitter" id="#p.AuthenticationType" name="provider" value="#p.AuthenticationType"><i class="fa fa-twitter"></i></button>
break;
case "Google":
<button type="submit" class="btn btn-xsm googleplus" id="#p.AuthenticationType" name="provider" value="#p.AuthenticationType"><i class="fa fa-google-plus"></i></button>
break;
case "Microsoft":
<button type="submit" class="btn btn-xsm microsoft" id="#p.AuthenticationType" name="provider" value="#p.AuthenticationType"><i class="fa fa-windows"></i></button>
break;
default:
<button type="submit" class="btn btn-xsm" id="#p.AuthenticationType" name="provider" value="#p.AuthenticationType">#p.AuthenticationType.ToString()</button>
break;
}
}
</span>
}
}
When you do #Html.Partial() and don't provide it a model, it uses the current (or parent, if you want to think of it that way) model instead. So when you do
#Html.Partial("../Account/_ExternalLoginsList")
Without the second parameter to specify the model, it provides the current one. You should be providing a view model to the partial like so:
#Html.Partial("../Account/_ExternalLoginsList", externalLoginsViewModel)
Otherwise you'll provide the current one, which is not the same type that is expected by the partial.
The ExternalLoginList partial expects a model to be passed to it.
#model WebPortal.Models.ExternalLoginListViewModel
You need to pass the model in here:
#Html.Partial("../Account/_ExternalLoginsList")
Like this:
#Html.Partial("../Account/_ExternalLoginsList", new ExternalLoginListViewModel())
OR
Put the partial's model in the parent's model
public class LoginViewModel
{
public ExternalLoginListViewModel externalLoginListViewModel;
}
and pass it to the partial.
#Html.Partial("../Account/_ExternalLoginsList", externalLoginListViewModel)
OR
I don't see any references to the model in the ExternalLoginList partial so you can probably just delete this line:
#model WebPortal.Models.ExternalLoginListViewModel