Passing Value from URL using RenderPartial to another View - c#

I have a View which uses #Html.RenderPartial for showing some data which is present on another View.
I want to send an ID present in the URL into the RenderPartial so that it can be utilized on the Other Page.
Following is my code of JobView.cshtml which uses #Html.RenderPartial:
#model NurseOneStop.SC.PostedJob
#{
ViewBag.Title = "JobView";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="row">
<div class="lstCard">
<div class="applied-view">
<p>
<b>Job Salary:</b> #Model.JobSalary
</p>
<p>
<b>Job Desc:</b> #Model.JobDesc
</p>
<p>
<b>Job Summary:</b> #Model.JobSummary
</p>
<p>
<b>Job Application Type:</b> #Model.JobApplicationType
</p>
<p>
<b>CategoryId:</b> #Model.Category
</p>
<p>
<b>Number Of Positions:</b> #Model.NumberOfPositions
</p>
<p>
<b>CreatedOn:</b> #Model.CreatedOn.ToString("MMM dd, yyyy")
</p>
<p>
<b>Skills:</b> #Model.SkillNames
</p>
<p>
<b>Status:</b> #if (Model.Status)
{
<span>Open</span>
}
else
{
<span>Class</span>
}
</p>
</div>
</div>
</div>
<hr />
<div class="row">
<div class="lstCard">
<h2>Applied Nurses List</h2>
#{
Html.RenderPartial("NurseListView", (List<NurseOneStop.SC.NurseProfile>)Model.AppliedNurses, new ViewDataDictionary { { "PostedJobId", Model.PostedJobId } });
}
</div>
</div>
<p class="back-tolist">
#Html.ActionLink("Back to List", "Index")
</p>
Below is my code for NurseListView.cshtml:
#model IEnumerable<NurseOneStop.SC.NurseProfile>
#foreach (var item in Model)
{
<div class="col-md-4 col-sm-6 col-xs-12">
<span><b style="color:#007976; font-weight:600;">#item.Title #item.FirstName #item.LastName</b></span><br />
<span><b>Profession:</b> #item.Profession</span><br />
<span><b>Mobile:</b> #item.PhoneNumber</span><br />
<span><b>Email:</b> #item.EmailId</span><br />
<span><b>Verified Email:</b> #(item.IsVerifiedEmail ? "Yes" : "No")</span><br />
<span><b>Verified Contact:</b> #(item.IsVerifiedContact ? "Yes" : "No")</span><br />
<span><b>Applied On:</b> #item.CreatedOn.ToString("dd-MMM-yyyy")</span><br />
<span><b>Skills:</b> #item.Skills</span><br />
<span><b>Address:</b> #item.AddressLine1, #item.AddressLine2 #item.ZipCode</span><br />
#*<span>#item.ProfileUrl</span>*#
<span>#item.CurrentPosition</span><br />
<span>#item.Summary</span><br />
<span>#item.PreferredJobLocation</span>
<p class="no-margin" style="text-align:right">
#Html.ActionLink("Download CV", "DownloadResume", "PostedJob", new { ResumeId = item.NurseResumeList[0].ResumeId , PostedJobId = item.PostedJobId}, new { #class = "btnViewJobDetails" })
View Profile
#Html.ActionLink("Message", "SendMessage", "Recruiter", new { NurseId = item.NurseId }, new { #class = "btnViewJobDetails" })
</p>
</div>
}
http://localhost:49509/PostedJob/JobView?PostedJobId=100162&returnUrl=%2FPostedJob%2FIndex
I want to pass PostedJobId which is shown in the URL on the click of Download CV option.
How to do that?

You have to use HttpContext.Current.Request.QueryString["PostedJobId"] in your partial view to access PostedJobId value from URL.
#Html.ActionLink("Download CV", "DownloadResume", "PostedJob", new { ResumeId = item.NurseResumeList[0].ResumeId , PostedJobId = Request.QueryString["PostedJobId"]}, new { #class = "btnViewJobDetails" })

You can add the following to your code:
#Html.ActionLink("Download CV", "DownloadResume", "PostedJob", new { ResumeId = item.NurseResumeList[0].ResumeId , PostedJobId = Request.QueryString["PostedJobId"]}, new { #class = "btnViewJobDetails" })

Related

Unable to bind data to the razor view even though the model is not null

Even though the model is not null the required html is not rendered. This is my razor view:
#model List<Product>
#{
ViewBag.Title = "Cart";
}
#for(int i=0;i<=Model.Count()-1;i++)
{
<p>foreach triggered</p>
var image = "~/images/" + Model[i].product_image_path;
<div class="row">
<div class="col">
<div class="row">
<div class="col-md-2">
<img src="#image" alt="No image" class="img-fluid" width="60" asp-append-version="true" />
</div>
<div class="col-md-4">
<div class="row">
<div class="col">
<p class="justify-content-md-start">#Model[i].ProductName</p>
</div>
</div>
<div class="row">
<div class="col">
<p>₹#Model[i].Price</p>
</div>
</div>
</div>
<div class="col-md-4">
<div class="row">
<div class="col-md-8">
#*change quantity button*#
<div class="input-group">
<button type="submit" class="btn btn-light"> - </button>
<input type="text" class="form-control" value="#Model[i].Quantity" readonly />
<button type="submit" class="btn btn-light"> + </button>
</div>
</div>
</div>
<br />
</div>
<div class="col-md-2">
<div class="row">
<div class="col">
<button class="btn btn-danger" type="button" id="button-minus">Remove</button>
</div>
</div>
</div>
</div>
</div>
</div>
}
Here is my get action method. This is basically retrieving the product from the models. I am returning an object of List<Product>. Trying to loop over it using for loop on razor view does not seem to work.
[HttpGet]
public IActionResult Cart()
{
var model = new CartProductViewModel();
var sessionId = HttpContext.Session.Id;
var allCartItems = context.cartItems;
var allProducts = context.products;
var currentCartItem = allCartItems.Where(p => p.Product.ProductId.Equals(sessionId)).Select(p=>p).ToList();
List<Product> products = new List<Product>();
foreach (var item in currentCartItem)
{
var id = item.Product.ProductId;
if (id is null) { return View("NotFound"); }
Product prod = allProducts.Where(p => p.ProductId.Equals(id)).Select(p=>p).Single();
products.Add(prod);
}
return View(products);
}

Pager in .Net Core 2.1

I have added ReflectionIT.Mvc.Paging from NuGet Link but I have a problem.
In a controller i have 2 methods, Index and Organizations. When I am on the view of Orginizations and press page with number "2" in controller goes to index and not on Organizations method.
How to force it to go on a method I want or to extend this #await this.Component.InvokeAsync("Pager", new { pagingList = this.Model }) to pass method name as parameter?
Controller:
public IActionResult Index()
{
return View();
}
public async Task<IActionResult> Organizations(int page=1)
{
var userlist = _context.Users.Include(u => u.UserRoles).ThenInclude(u => u.Role).Where(o => o.UserRoles.All(r => r.Role.Name == "Company") && o.IsActive == true).AsNoTracking().OrderByDescending(o => o.Company);
var model = await PagingList.CreateAsync(userlist, 2, page);
return View(model);
}
View:
#model ReflectionIT.Mvc.Paging.PagingList<CharityProject.Models.ApplicationUser>
#using ReflectionIT.Mvc.Paging
#addTagHelper *, ReflectionIT.Mvc.Paging
#{
ViewData["Title"] = "Organizations";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container py-lg-5 py-md-5 py-sm-4 py-4">
<h2 class="pageTitles">Organizations</h2>
<div class="row">
<nav aria-label="NewsFeed navigation example">
#await this.Component.InvokeAsync("Pager", new { pagingList = this.Model })
</nav>
<br />
#foreach (var item in Model)
{
<div class="col-lg-4 col-md-6 col-sm-6 product-men women_two">
<div class="product-toys-info">
<div class="men-pro-item">
<div class="men-thumb-item">
#if (item.Logo != null)
{
<img src=#Url.Content(item.Logo.Replace("//","/").Replace("///","/")) class="img-thumbnail img-fluid" alt="">
}
<div class="men-cart-pro">
<div class="inner-men-cart-pro">
View
</div>
</div>
</div>
<div class="item-info-product">
<div class="info-product-price">
<div class="grid_meta">
<div class="product_price">
<h4>
<a href=#Url.Action("OrganizationInfo","Home",new { id=item.Id})>#item.Company</a>
</h4>
<p>#item.Moto</p>
</div>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
}
<br />
<nav aria-label="NewsFeeds navigation example">
<vc:pager paging-list="#Model" />
</nav>
</div>
</div>
You can set the Action property to PagingList object :
var model = await PagingList.CreateAsync(userlist, 2, page);
model.Action = "Organizations";

MVC ViewModel HttpPost return value has null values

I spent some time on this problem. I'm passing a ViewModel back from my View to the Controller via a form HttpPost. However, only SelectedItemId has value. Users and Rights are null.
View model UserRightViewModel
public class UserRightViewModel
{
public string SelectedItemId { get; set; }
public SelectList Users;
public List<RightViewModel> Rights { get; set; }
}
View model RightsViewModel
public class RightsViewModel
{
public int ID { get; set; }
public string Name{ get; set; }
public bool isSelected { get; set; }
}
Controller Post
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(UserRightsViewModel _viewModel)
{
UserRightsViewModel viewModel = _viewModel;
/*value _viewModel = null for Users and Rights
/* code stuff */
return View(viewModel);
}
View
#model Web.ViewModels.UserRightsViewModel
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
#ViewBag.Title
</h1>
#*<ol class="breadcrumb">
<li><i class="fa fa-dashboard"></i> Home</li>
<li>Examples</li>
<li class="active">Blank page</li>
</ol>*#
</section>
<!-- Main content -->
<section class="content">
<!-- Default box -->
<div class="box">
<div class="box-header with-border">
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip" title="Collapse">
<i class="fa fa-minus"></i>
</button>
<button type="button" class="btn btn-box-tool" data-widget="remove" data-toggle="tooltip" title="Remove">
<i class="fa fa-times"></i>
</button>
</div>
</div>
<br />
<div class="form-group">
#Html.LabelFor(model => model.SelectedItemId, "User", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.SelectedItemId, Model.Users, new { onchange = "redirect(this.value)", #class = "form-control" })
#Html.ValidationMessageFor(model => model.SelectedItemId)
</div>
</div>
<br />
<div class="box-body">
#for (int i = 0; i < Model.Rights.Count(); i += 2)
{
<div class="row form-group">
<div class="col-md-6">
<div class="row">
<div class="col-md-4">
<div class="col-md-6">
</div>
<div class="col-md-6">
#Html.CheckBoxFor(model => model.Rights.ElementAt(i).isSelected, new { #class = "checkbox checkbox-center" })
#Html.ValidationMessageFor(model => model.Rights.ElementAt(i).isSelected, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-8">
#Model.Rights.ElementAt(i).Denumire
</div>
</div>
</div>
<div class="col-md-6">
<div class="row">
<div class="col-md-4">
<div class="col-md-6">
</div>
<div class="col-md-6">
#Html.CheckBoxFor(model => model.Rights.ElementAt(i + 1).isSelected, new { #class = "checkbox checkbox-center" })
#Html.ValidationMessageFor(model => model.Rights.ElementAt(i + 1).isSelected, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-8">
#Model.Rights.ElementAt(i + 1).Name
</div>
</div>
</div>
</div>
}
<br />
<br />
<div class="form-group">
<div class="row">
<div class="col-md-6">
<div class="col-md-9">
</div>
<div class="col-md-3">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</div>
<div class="col-md-6">
#Html.ActionLink("Cancel", "Index", null, new { #class = "btn btn-danger" })
</div>
</div>
</div>
</div>
</div>
</section>
</div>
}
I have no idea why some values are null. Why some of values are sent and some not?
Users is null because your not (and nor should you) creating and input for each property of each SelectListItem in the SelectList (if you need to return the view you re-populate the value in the POST method). And in any case, its a field, not a property (has no { get; set; }) so the DefaultModelBinder cannot set it).
Rights is null because you cannot use .ElementAt() to generate form controls for a collection (inspect the html your generating and you will see that the name attributes have no relationship to your model). The name attributes need to be
<input name="Rights[0].ID" ... />
<input name="Rights[0].Name" ... />
<input name="Rights[0].isSelected" ... />
<input name="Rights[1].ID" ... />
<input name="Rights[1].Name" ... />
<input name="Rights[1].isSelected" ... />
....
Note that your only generating a for control for the isSelected property which on its own would be meaningless in the POST method and you will an least want to include a hidden input for the ID property.
It appears from your code that you want to generate a 2 column layout, in which case your code should be (simplified)
<div class="row form-group">
#for(int i = 0; i < Model.Rights.Count; i++)
{
<div class="col-md-6">
#Html.HiddenFor(m => m.Rights[0].ID)
#Html.CheckBoxFor(m => m.Rights[0].isSelected)
</div>
// End current 'row' and start a new one every 2nd item
if ((i + 1) % 2 == 0)
{
#:</div><div class="row form-group">
}
}
</div>
Hi here is answer for your doubt, some values are posting and some values are not.
Actually you are getting the correct result and everything works perfectly
I said this because, if you bind selectedid and selectlistitem to the dropdownlistfor helper, then you will get only selectedid which was assigned as a name for the dropdownlist control. so when post, browser has sent name value pair.
This is same reason for checkbox also , which property has binded to the name that only you will get it in the post.
Hope above information was helpful
Thanks
Karthik
I can see you put submit button outside form. so form not submitting property.

'System.Data.Entity.DynamicProxies.User_',this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[Oblig1.Models.Item]'

I am currently getting the error "The model item passed into the dictionary is of type 'System.Data.Entity.DynamicProxies.User_546F9926F8DC53E2EF66BA48BE431DF1B26DEBEFA54B0597E60AEB1839DD022C', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[Oblig1.Models.Item]'."
I am trying to list out the view _Minside.html with a single User but keep getting this error, anyone who could lend a helping hand?
_Minside.html:
#model Oblig1.Models.User
<table class="table">
#Model.Firstname
#Model.Surname
#Model.Email
#Model.Address
#Model.Password
#Model.Phonenr
#Model.Postcode
</table>
This is a partial which comes through Minside.html:
#model Oblig1.Models.User
<br />
<br />
<br />
<!-- Nav tabs -->
<ul class="nav nav-tabs" role="tablist">
<li class="active">Kontoinformasjon</li>
<li>Ordrehistorikk</li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div class="tab-pane active" id="home">
<br />
<br />
#Html.Partial("_Minside")
</div>
<div class="tab-pane" id="profile">Ordrehistorikk</div>
<div class="tab-pane" id="messages">...</div>
<div class="tab-pane" id="settings">...</div>
</div>
This view is opened by the link in the view _Layout which contains this model:
#model IEnumerable<Oblig1.Models.Item>
#Html.ActionLink(" MinSide", "Minside", "", new { #class = "glyphicon glyphicon-user" })
UserController:
public ActionResult Minside()
{
var db = new PastaContext();
string compareEmail = (string)Session["User"];
User foundUser = db.Users.Find(compareEmail);
if(foundUser == null)
{
return RedirectToAction("Index");
}
else
{
return View(foundUser);
}
}

ajax updatetargetid with mvc partial views not rendering properly

I have a view which contains a tab layout, each tab contains a form which I am submitting through ajax.beginform. If the modelstate is not valid I return the view which is where I cannot work out how to render the view properly. Currently when I submit one of the forms it renders the whole page again within my tab, which I don't want. I thought using ajax updatetargetid I could render the div that needs replacing, but as I said it renders the whole page within my tab.
View
#model Trakman_Portal_Administration.Models.VehList
#using Trakman_Portal_Administration.Models
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
#*<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>*#
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function () {
$("#tabs").tabs();
});
</script>
#{
ViewBag.Title = "Edit";
}
<div class="editBanner">
<div class="editor-label">
#* #{
string custCode = ViewBag.custCode;
}*#
#* <h2>#Html.Label(custCode, custCode )</h2>*#
<h2>#Html.Label(Model.Column_8, Model.Column_8 )</h2>
</div>
</div>
<h3 style="font-size:20px">Edit</h3>
<br />
#*
TAB 1 VEHICLE DATA SAVED TO VEHLIST
*#
<div id="tabs">
<ul>
<li>Vehicle</li>
<li>Page 1</li>
<li>Page 2</li>
</ul>
<div id="tabs-1">
#using (Ajax.BeginForm("Edit",null, new AjaxOptions
{
OnSuccess = "OnSuccessEditVehicle",
OnFailure = "OnFailureEditVehicle",
HttpMethod = "Post",
UpdateTargetId = "tabs-1"
}, new {id="EditVehicle"}))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>VehList</legend>
#Html.EditorForModel()
</fieldset>
<div style="position:relative;left:750px">
#Html.ActionLink("Back to List", "Index", new {custCode= ViewBag.custCode, conName = ViewBag.connectionName}) |
<input type="submit" value="Save" /></div>
}
#*
TAB 1 VEHICLE DATA SAVED TO VEHICLEDATA
*#
</div>
<div id="tabs-2">
#{
VehicleData vd = ((Trakman_Portal_Administration.Controllers.VehicleController)this.ViewContext.Controller).EditVDPartial(Model.Column_0);
}
#Html.Partial("EditVDPartial", vd)
#* <div style="position:relative;left:750px">
#Html.ActionLink("Back to List", "Index", new {custCode= ViewBag.custCode, conName = ViewBag.connectionName}) |
<input type="button" value="Save" onclick="submitVehicleDataForm()" /></div>*#
</div>
#*
TAB 3 VEHICLE DATA SAVED TO VEHICLE
*#
<div id="tabs-3">
#{
vehicle v = ((Trakman_Portal_Administration.Controllers.VehicleController)this.ViewContext.Controller).EditPartial(Model.Column_0);
}
#Html.Partial("EditPartial", v)
<div style="position:relative;left:750px">
#Html.ActionLink("Back to List", "Index", new {custCode= ViewBag.custCode, conName = ViewBag.connectionName}) |
<input type="submit" value="Save" /></div>
</div>
</div>
<br />
Controller
public ActionResult Edit(VehList vehlist)
{
tedb = new trakman_Entities(System.Web.HttpContext.Current.Session["connection"].ToString());
if (ModelState.IsValid)
{
vehlist.Column_8 = System.Web.HttpContext.Current.Session["staticCustCode"].ToString();
tedb.VehLists.Attach(vehlist);
tedb.ObjectStateManager.ChangeObjectState(vehlist, System.Data.EntityState.Modified);
tedb.SaveChanges();
var cust = tedb.customers.First(c => c.code == vehlist.Column_8);
//return RedirectToAction("Index", new { custCode = cust.code, conName = System.Web.HttpContext.Current.Session["connectionName"]});
}
ViewBag.Column_8 = new SelectList(tedb.customers, "code", "name", vehlist.Column_8);
return View(vehlist);
}

Categories

Resources