url.Action not Invoking method in controller - c#

I have a simple page where i try to load an image from the database.
The method in controller is not responding to the url.Action call.
i have a page in another area which is identical to this page and it is working fine there
(I literally copy the html from the working view to this view and the method is still not invoked).
On the browser is get :
GET https://localhost:7260/admin/AdImage/MyAction?path=img%2Fjpg net::ERR_BLOCKED_BY_CLIENT
Not getting this error in the other working page.
Here is the view calling the controller method:
#model Click2Lock.Models.ForCompListVM
#{ ViewData["Title"] = "Home Page"; }
<body>
<div class="col-4" >
<div id="imageDiv">
<img src= '#Url.Action("MyAction", "AdImage", new{path="img/jpg"})'/> #* NOT RESPONDING *#
</div>
<div class="form-group row">
<div class="col-2">
<label asp-for="forCompList.CompId">Company</label>
</div>
<div class="col-8">
#Html.DropDownListFor(m => m.forCompList.CompId, Model.CompList,
new { #class = "form-control" })
</div>
</div>
<div class="col-2 text-right">
<button class="btn btn-primary" style="background-color:forestgreen" onclick="LoadImage()">
<i class="fa fa-refresh"></i> Load Company Image</button>
</div>
</div>
</body>
controller method:
[HttpGet]
[Route("compmanager/AdImage/MyAction")]
public FileContentResult MyAction()
{
byte[] img = new byte[100000];
ApplicationUser appUser =
_unitOfWork.ApplicationUser.GetAll().Where(a => a.UserName == User.Identity.Name).FirstOrDefault();
if (appUser != null)
{
img = _unitOfWork.Company.GetAll().Where(a => a.Id == appUser.CompanyId).
Select(a => a.PhotoAd).FirstOrDefault();
}
if (img == null)
{
return null;
}
return new FileContentResult(img, "img/jpg");
}

Related

Submitting a form from a partial view

I'm trying to submit a form from a modal generated in a partial view. And I don't know how to get back the submitted form.
Here is the view:
#model Myproject.ViewModels.GetMonitorFromDeviceViewModel
#{
ViewBag.Title = "GetMonitorFromDevice";
Layout = "~/Views/Shared/ManagementPage.cshtml";
}
<div id="Accordion">
#{
foreach (var type in Model.AvailableTypesAvailableMonitors)
{
<div class="card">
<div class="card-header">
<a class="card-link" data-toggle="collapse" data-parent="#accordion" href="##type">
#type
</a>
</div>
<div id="#type" class="collapse show">
<div class="card-body">
#{
foreach (var monitor in Model.ActiveMonitors)
{
if (monitor.Type == #type)
{
<p>
#monitor.Name
<span class="btn btn-xs btn-primary btnEdit" onclick="createModal('#Url.Action("NameMonitor", "DeviceManager" , new { idDevice = monitor.DeviceOwner.ID, monitorName = monitor.Name })')">Details</span>
</p>
}
}
}
</div>
</div>
</div>
}
}
</div>
And here is my modal at the bottom of the page:
<div class="modal fade" id="myModal" role="dialog" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<div class="modal-content" id="modelContent">
</div>
</div>
</div>
<script>
function createModal(url) {
$('#modelContent').load(url);
$('#myModal').modal('show');
}
</script>
And finally, here is my partial view that is displayed as a modal:
#model MyProject.ViewModels.NameMonitorModal
#using (Html.BeginForm("NameMonitor", "DeviceManager", FormMethod.Post))
{
<div class="modal-body">
<div class="form-group">
#Html.LabelFor(model => model.NewName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.NewName, new { htmlAttributes = new { #class = "form-control", #Value = Model.TrueName } })
#Html.ValidationMessageFor(model => model.NewName, "", new { #class = "text-danger" })
</div>
</div>
#Html.HiddenFor(model => model.TrueName)
#Html.HiddenFor(model => model.IdDevice)
</div>
<div class="modal-footer">
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save name" class="btn btn-default" data-dismiss="modal" />
</div>
</div>
</div>
}
In my controller, I have an action for my partial view called ActionResult NameMonitor.
In order to catch the submited form, I tried to add another action with the [HttpPost] tag with the same name but doesn't work. I also tried to use the main page action with the [HttpPost] tag but it doesn't work either. As you can see, I have specified the action and controller in the form itself but its still not working.
Now, I'm a little bit out of idea of how I can get the information from my modal back.
data-dismiss="modal" will close the modal without submitting the form, see Dismiss and submit form Bootstrap 3
You can change the submit button to call a JavaScript function to submit the form, then close the modal.
function submitModal() {
$('#myFormId').submit();
$('#myModal').modal('hide');
}

Authorization: users able to edit their own details when loggedin

I have an application where I want Volunteers to be able to help with a Ceremony.
I would like them to be log in and click a button, this brings them to a page where their details appear and a list of Ceremonies they can apply for. I have that page working but I have no way of getting the current user logged in.
Also, for clarification: I have a Volunteer entity which holds the data and then a separate user entity. The username for a Volunteer is the same as their user entity.
I want to:
Compare the Username to the Volunteer Username and get the
VolunteerId.
2.This will then be used to edit/join a ceremony for that particular volunteer.
Here's my Volunteer Controller methods:
// GET:
public ActionResult VolunteerCeremony(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
string userName = string.Empty;
var getVolunteerId = (from u in db.Volunteers
where WebSecurity.CurrentUserName == u.Username
select u.VolunteerId).SingleOrDefault();
Volunteer v = (Volunteer)(from k in db.Volunteers
where getVolunteerId == k.VolunteerId
select k).SingleOrDefault();
if (v == null)
{
return HttpNotFound();
}
PopulateAssignedCeremonyData(v);
return View(v);
}
// GET:
public ActionResult VolunteerHub()
{
return View();
}
// POST: /Player/VolunteerCeremony/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult VolunteerCeremony(int? id, string[] selectedOptions)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var getVolunteerId = (from u in db.Volunteers
where WebSecurity.CurrentUserName == u.Username
select u.VolunteerId).SingleOrDefault();
var v = (Volunteer)(from k in db.Volunteers
where getVolunteerId == k.VolunteerId
select k).SingleOrDefault();
try
{
UpdateVolunteerCeremonies(selectedOptions, v);
db.Entry(v).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
catch (RetryLimitExceededException /* dex */)
{
//Log the error (uncomment dex variable name and add a line here to write a log.
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
}
PopulateAssignedCeremonyData(v);
return View(v);
}
And then my Razor pages, the first which I want the user to click a link to bring them to the edit/join ceremony page:
#model PIMS.Entities.Volunteer
#{
ViewBag.Title = "VolunteerHub";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<li>#Html.ActionLink("Join Ceremony", "VolunteerCeremony", "Volunteers", null, new { id = #model.VolunteerId })</li>
This gives me an error on the new { id = #model.VolunteerId }
Then the page which I want to get to:
#model PIMS.Entities.Volunteer
#using Microsoft.AspNet.Identity
#{
ViewBag.Title = "VolunteerCeremony";
}
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<h2>Apply for Ceremony</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.VolunteerId)
<div class="form-group">
#Html.LabelFor(model => model.Name, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.VolunteerRole, "Volunteer Role", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.VolunteerRole, new { #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.VolunteerRole)
</div>
</div>
</div>
<div class="row">
<div class="col-md-2"> </div>
<div class="form-group col-md-4">
<label class="control-label">Assigned Ceremonies</label>
#Html.ListBox("selectedOptions", (MultiSelectList)ViewBag.SelectedCeremonies, new { #class = "form-control" })
</div>
<div class="form-group col-md-1" style="text-align:center">
<div class="form-group">
<button type="button" id="btnRight" class="btn btn-warning btn-lg">
<span class="glyphicon glyphicon-arrow-right"></span>
</button>
</div>
<div class="form-group">
<button type="button" id="btnLeft" class="btn btn-success btn-lg">
<span class="glyphicon glyphicon-arrow-left"></span>
</button>
<div></div>
</div>
</div>
<div class="form-group col-md-4">
<label class="control-label">Available Ceremonies</label>
#Html.ListBox("availOptions", (MultiSelectList)ViewBag.AvailCeremonies, new { #class = "form-control" })
</div>
<input type="submit" id="btnSubmit" value="Save" class="btn btn-default" />
</div>
<div style="text-align:center;">
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/multisel")
}
Does anyone have any experience with this as it sort of key to my application!
in mvc there is something called session variables, its just like app.config variables, you declare them like this in the controller
Session["Volunteer"] = "volunteer1";
once declared they will remain declared for the entire session.
then you write code for the logoff to reset the Session variable to something that your code handles as no-one logged in or just null.

Working with attribute routing in mvc

On my login page I have a dropdownlist to change the culture of the application for which I am doing a Ajax call to set the culture. By default I have set to 'en_US'.
My issue is when I am login directly without changing the culture I am able to login successfully, but when I change the culture and tries to login, I am not able to do that. Is this happening because of AJAX call made, which makes custom attribute not registered ?
Also, my login method has a custom attribute defined. Below is the code.
AJAX Call
$('#ddlLanguages').change(function () {
var val = $('#ddlLanguages').val()
createCookie('culturecookie', val, 7);
$.ajax({
type: "POST",
url: '/Account/GetCultureNew',
data: { culturename: val },
success: function (result) {
$("#logo-group").html('');
$(document.body).html('');
$(document.body).html(result);
},
error: function (data) {
//alert('Error');
}
});
});
Ajax Method in controller
[HttpPost]
public ActionResult GetCultureNew(string culturename)
{
if (!string.IsNullOrEmpty(culturename) & culturename.Contains("#"))
{
string[] strdata = culturename.Split('#');
if (strdata.Length > 0)
{
AppTenant tenant = HttpContext.Session.GetObjectFromJson<AppTenant>("TenantInfo");
if (tenant != null)
{
tenant.LoggedInCulture = strdata[0];
tenant.LanguageID = Convert.ToInt32(strdata[1]);
HttpContext.Session.SetObjectAsJson("TenantInfo", tenant);
}
}
}
List<SelectListItem> items = new List<SelectListItem>();
items = HttpContext.Session.GetObjectFromJson<List<SelectListItem>>("LanguageData");
foreach (var item in items)
{
if (item.Value == culturename)
{
item.Selected = true;
}
else
{
item.Selected = false;
}
}
var itemsString = JsonConvert.SerializeObject(items);
CookieOptions obj = new CookieOptions();
obj.Expires = DateTime.Now.AddMonths(3);
Response.Cookies.Append("Languagelist", itemsString, obj);
var viewModel = new LMS_User { ReturnUrl = string.Empty, LanguageList = items };
return View("Login", viewModel);
}
Login Method
[HttpPost]
[AllowAnonymous]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
[Route("Admin/Login/{clietname}")]
public async Task<IActionResult> Login([Bind(include: "Email,Password,RememberMe")] LMS_User model, string returnUrl)
{
// my login logic
}
EDIT :- 1
Login partial View
<div class="col-xs-12 col-sm-12 col-md-5 col-lg-4">
<div class="well no-padding">
<form action="#Url.Action("login", "account")" method="POST" id="login-form" class="smart-form client-form">
<header>
#obj["SingnIn"]
</header>
#Html.AntiForgeryToken()
<fieldset>
<section>
<label asp-for="LanguageList">#obj["LanguageList"] </label>
#Html.DropDownList("Languages", Model.LanguageList, null, new { id = "ddlLanguages", #class = "form-control" })
</section>
<section>
<label asp-for="Email">#obj["Email"]</label>
<label class="input">
<i class="icon-append fa fa-user"></i>
#Html.TextBoxFor(m => m.Email, new { #class = "form-control" })
<b class="tooltip tooltip-top-right"><i class="fa fa-user txt-color-teal"></i>>#obj["tooltipEmail"]</b>
<span asp-validation-for="Email" class="text-danger"></span>
</label>
</section>
<section>
<label asp-for="Password">#obj["Password"]</label>
<label class="input">
<i class="icon-append fa fa-lock"></i>
#Html.PasswordFor(m => m.Password, new { #class = "form-control" })
<b class="tooltip tooltip-top-right"><i class="fa fa-lock txt-color-teal"></i>#obj["tooltippassword"] </b>
<span asp-validation-for="Password" class="text-danger"></span>
</label>
<div class="note">
<i class="fa fa-frown-o"></i> #obj["Forgot_password?"]
</div>
</section>
<section>
<label class="checkbox">
<input asp-for="RememberMe" />
<i></i>#obj["Remember_Me"]
</label>
</section>
<footer>
<button type="submit" class="btn btn-primary">
#obj["SingnIn"]
</button>
</footer>
</fieldset>
</form>
</div>
#{ await Html.RenderPartialAsync("_SocialMedia"); }
Edit 2:-Entire login view
<div id="content" class="container">
<div class="row">
#{ await Html.RenderPartialAsync("_LoginText"); }
#{ await Html.RenderPartialAsync("_LoginPartial"); }
</div>
</div>
However if I add location.reload() in AJAX success function, then by changing the culture I can login successfully.
Any help on this appreciated !
When you do the $(document.body).html(result);
The action part of the form goes missing. Hence it does not know where to post to.
Hope i have been of some help :)

MVC Model is empty when postback

I have this model, Customer . When i get the information with an id, it works just fine.
Like ;
/Customer/Entity/5
#model ProgSpace.Models.Customer
#{
ViewBag.Title = Model.Name;
Layout = "~/Views/Shared/_MainLayout.cshtml";
}
#section bodypane
{
#using (Html.BeginForm("Entity", "Customer", FormMethod.Post, new { #enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="col-md-12">
<div class="col-md-1">
<label>Customer No:</label>
<h4># #(Model.ID) </h4>
</div>
<div class="clearfix"></div><br />
<div class="col-md-2">
<div class="col-md-12">
<div class="col-md-12 fileupload fileupload-exists" data-provides="fileupload">
<div class="fileupload-preview fileupload-exists thumbnail" style="width: 200px; height: 150px;">
<img src="#Model.Picture.Path" />
</div>
<div>
<span class="btn btn-default btn-file">
<span class="fileupload-new">Add Pic </span>
<span class="fileupload-exists">Change</span><input name="file" id="file" type="file">
</span>
Remove
</div>
</div>
</div>
</div>
<div class="col-md-10">
<div class="col-md-3">
<label>Name *</label>
#Html.TextBoxFor(model => model.Name, new { #class = "form-control"})
</div>
<div class="col-md-3">
<label>Company</label>
#Html.TextBoxFor(model => model.Contact.Company, new { #class = "form-control"})
</div>
<div class="col-md-3">
<label>Phone </label>
#Html.TextBoxFor(model => model.Contact.Phone, new { #class = "form-control" })
</div>
</div>
<div class="clearfix"><br /></div>
<p> </p>
<div class="col-md-12">
<div class="btn-group">
<button class="btn btn-danger btn-lg">Cancel</button>
<button type="submit" class="btn btn-success btn-lg">Send</button>
</div>
</div>
</div>
}
}
And in the controller i have these actions.
public ActionResult Entity(int id)
{
Customer cust= sis.Customers.Where(t => t.ID == id).FirstOrDefault();
return View(cust);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Entity(Customer cust, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
/* Do something */
}
else
{
}
return View(cust);
}
When the verb is GET , it's fine. But when i post this form and when the second action (HttpPost action) kicks in , view throws an error..
Object reference not set to an instance of an object
which marks the Model.ID is null in the view.
<div class="col-md-1">
<label>Customer No:</label>
<h4># #(Model.ID) </h4> ---> THIS HERE THROWS NULL EXCEPTION
</div>
I've tried to add a HiddenFor for the Model.ID like
#Html.HiddenFor(t => t.ID)
but it didn't change anything.
How do i get back to the same view with the same context again ?

load another View page only on button click on the same page in mvc3

Below is my View page in which I have called action PromotionalMis and below this view code I have written my action
#using (Html.BeginForm("PromotionalMis", "Home", FormMethod.Post))
{
<div class="loginn" style="width:600px;">
<div class="logintext" style="width:154px;">
#Html.LabelFor(model => model.SongId, "Song Name")
</div>
<div class="mistype">
<select id="ddlsongs" name="ddlsongs" class="state" required="required">
</select>
</div>
</div>
<div class="loginn" style="width:600px;">
<div class="logintext" style="width:154px;">
</div>
<div class="generate">
<input type="submit" name="button" value="Generate" id="btn"/>
</div>
</div>
}
Below is my Action in Home Controller. I want to do things is that whenever I select albumname and song name from dropdownlist and when I will click on button My PromotionalMis view page should be visiblee on the same page
[HttpPost]
public ActionResult PromotionalMis(string ddlsongs)
{
if (Session["user"] != null && Session["user"].ToString() == "MISADMIN")
{
if (ddlsongs != "0")
{
string sSongName = "";
int iId = Convert.ToInt32(ddlsongs);
List<CRBT_Promotion> ss = new List<CRBT_Promotion>();
using (crbt_onwebEntities dbcontext = new crbt_onwebEntities())
{
ss = (from z in dbcontext.CRBT_Promotion where z.id == iId select z).ToList();
}
foreach (var ssname in ss)
{
sSongName = ssname.SongName.ToString();
}
Session["ss"] = sSongName;
ViewBag.songformis = sSongName;
}
return PartialView("PromotionalMis");
}
else
{
return RedirectToAction("LogOn");
}
}
#using (Ajax.BeginForm("ActionName", "Home", new AjaxOptions {HttpMethod="POST", UpdateTargetId = "filesBody" ,InsertionMode = InsertionMode.Replace}))
{
<div class="loginn" style="width:600px;">
<div class="logintext" style="width:154px;">
#Html.LabelFor(model => model.SongId, "Song Name")
</div>
<div class="mistype">
<select id="ddlsongs" name="ddlsongs" class="state" required="required">
</select>
</div>
</div>
<div class="loginn" style="width:600px;">
<div class="logintext" style="width:154px;">
</div>
<div class="generate">
<input type="submit" name="button" value="Generate" id="btnclick"/>
</div>
</div>
}
<div id="filesBody"></div
its working well

Categories