An error about my asp.net mvc project - asp.net-mvc

I have a problem from my Asp.net MVC Blog website project.
I am filling textbox on admin website from this picture
but website any operation so its can't operation on database.
I sent you project code about my website project error.
public class AdminMakaleController : Controller
{
blogDB db = new blogDB();
// GET: AdminMakale
public ActionResult Index()
{
var makales = db.Makales.ToList();
return View(makales);
}
// GET: AdminMakale/Details/5
public ActionResult Details(int id)
{
return View();
}
// GET: AdminMakale/Create
public ActionResult Create()
{
ViewBag.KategoriId = new SelectList(db.Kategoris, "KategoriId", "KategoriAdi");
return View();
}
// POST: AdminMakale/Create
[HttpPost]
public ActionResult Create(Makale makale,string etiketler,HttpPostedFileBase Foto)
{
try
{
db.Makales.Add(makale);
db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}

Related

Stimulsoft options to define actions loaded with incorrect route

I'm using Stimulsoft report on a .net core application include area, when I define report actions in StiNetCoreDesignerOptions method and run application actions called with incorrect route like this:
[area]/[action]/[controller]
in my view:
#Html.StiNetCoreDesigner(new StiNetCoreDesignerOptions()
{
Actions =
{
GetReport ="GetReport",
PreviewReport = "PreviewReport",
DesignerEvent = "DesignerEvent",
}
})
and in my controller:
[Area(AreaConstants.Automation)]
[Route("[area]/letter-print/[action]")]
public class LetterPrintController : Controller
{
[HttpGet]
public IActionResult Index()
{
return View();
}
[HttpGet]
public IActionResult GetReport()
{
StiReport report = new StiReport();
report.Load(StiNetCoreHelper.MapPath(this, "wwwroot/Reports/TwoSimpleLists.mrt"));
return StiNetCoreDesigner.GetReportResult(this, report);
}
[HttpGet]
public IActionResult PreviewReport()
{
var data = new DataSet("Demo");
data.ReadXml(StiNetCoreHelper.MapPath(this, "wwwroot/Reports/Data/Demo.xml"));
StiReport report = StiNetCoreDesigner.GetActionReportObject(this);
report.RegData(data);
return StiNetCoreDesigner.PreviewReportResult(this, report);
}
[HttpGet]
public IActionResult DesignerEvent()
{
return StiNetCoreDesigner.DesignerEventResult(this);
}
}
finally get this error:
GET https://localhost:44379/Automation/DesignerEvent/LetterPrint?stiweb_component=Designer&stiweb_action=Resource&stiweb_cachemode=cache&stiweb_version=2019.3.5&stiweb_data=DesignerScripts net::ERR_ABORTED 404
Uncaught ReferenceError: StiMobileDesigner is not defined

Generic class to identify Current Session information in ASP.Net MVC application

I'm developing a simple Custom Role-based Web Application using ASP.Net MVC, In my login Action, I'm creating a Profile session as below:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
using (HostingEnvironment.Impersonate())
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
var employeeProfile = AccountBal.Instance.GetEmployee(loginId);
Session["Profile"] = employeeProfile;
FormsAuthentication.SetAuthCookie(model.UserName, true);
}
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", #"The user name or password provided is incorrect.");
return View(model);
}
}
And I'm checking this or using this session in all Controller Actions as below:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateOrEdit(MyModel model)
{
var employee = (Employee) Session["Profile"];
if (employee == null)
return RedirectToAction("Login", "Account");
if (ModelState.IsValid)
{
// Functionality goes here....
}
}
Is there any way I can move this piece of session checking code in a base class or centralized class? so that, I do not need to check it every time in a Controller Actions instead I will access the properties directly
say,
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateOrEdit(MyModel model)
{
var employee = _profileBase.GetCurrentProfile();
if (employee == null)
return RedirectToAction("Login", "Account");
if (ModelState.IsValid)
{
// Functionality goes here....
}
}
Create a base controller that contains your GetCurrentProfile method to retrieve current user profile like
public class BaseController : Controller
{
public Employee GetCurrentProfile()
{
return (Employee)Session["Profile"];
}
public bool SetCurrentProfile(Employee emp)
{
Session["Profile"] = emp;
return true;
}
}
And inherit your desired controller with above BaseController and access your GetCurrentProfile method like below
public class HomeController : BaseController
{
public ActionResult SetProfile()
{
var emp = new Employee { ID = 1, Name = "Abc", Mobile = "123" };
//Set your profile here
if (SetCurrentProfile(emp))
{
//Do code after set employee profile
}
return View();
}
public ActionResult GetProfile()
{
//Get your profile here
var employee = GetCurrentProfile();
return View();
}
}
GetCurrentProfile and SetCurrentProfile directly available to your desired controller because we directly inherit it from BaseController.
You may usetry/catch in above code snippet.
Try once may it help you

Can we pass model as a parameter in RedirectToAction?

I want to know, there is any technique so we can pass Model as a parameter in RedirectToAction
For Example:
public class Student{
public int Id{get;set;}
public string Name{get;set;}
}
Controller
public class StudentController : Controller
{
public ActionResult FillStudent()
{
return View();
}
[HttpPost]
public ActionResult FillStudent(Student student1)
{
return RedirectToAction("GetStudent","Student",new{student=student1});
}
public ActionResult GetStudent(Student student)
{
return View();
}
}
My Question - Can I pass student model in RedirectToAction?
Using TempData
Represents a set of data that persists only from one request to the
next
[HttpPost]
public ActionResult FillStudent(Student student1)
{
TempData["student"]= new Student();
return RedirectToAction("GetStudent","Student");
}
[HttpGet]
public ActionResult GetStudent(Student passedStd)
{
Student std=(Student)TempData["student"];
return View();
}
Alternative way
Pass the data using Query string
return RedirectToAction("GetStudent","Student", new {Name="John", Class="clsz"});
This will generate a GET Request like Student/GetStudent?Name=John & Class=clsz
Ensure the method you want to redirect to is decorated with [HttpGet] as
the above RedirectToAction will issue GET Request with http status
code 302 Found (common way of performing url redirect)
Just call the action no need for redirect to action or the new keyword for model.
[HttpPost]
public ActionResult FillStudent(Student student1)
{
return GetStudent(student1); //this will also work
}
public ActionResult GetStudent(Student student)
{
return View(student);
}
Yes you can pass the model that you have shown using
return RedirectToAction("GetStudent", "Student", student1 );
assuming student1 is an instance of Student
which will generate the following url (assuming your using the default routes and the value of student1 are ID=4 and Name="Amit")
.../Student/GetStudent/4?Name=Amit
Internally the RedirectToAction() method builds a RouteValueDictionary by using the .ToString() value of each property in the model. However, binding will only work if all the properties in the model are simple properties and it fails if any properties are complex objects or collections because the method does not use recursion. If for example, Student contained a property List<string> Subjects, then that property would result in a query string value of
....&Subjects=System.Collections.Generic.List'1[System.String]
and binding would fail and that property would be null
[HttpPost]
public async Task<ActionResult> Capture(string imageData)
{
if (imageData.Length > 0)
{
var imageBytes = Convert.FromBase64String(imageData);
using (var stream = new MemoryStream(imageBytes))
{
var result = (JsonResult)await IdentifyFace(stream);
var serializer = new JavaScriptSerializer();
var faceRecon = serializer.Deserialize<FaceIdentity>(serializer.Serialize(result.Data));
if (faceRecon.Success) return RedirectToAction("Index", "Auth", new { param = serializer.Serialize(result.Data) });
}
}
return Json(new { success = false, responseText = "Der opstod en fejl - Intet billede, manglede data." }, JsonRequestBehavior.AllowGet);
}
// GET: Auth
[HttpGet]
public ActionResult Index(string param)
{
var serializer = new JavaScriptSerializer();
var faceRecon = serializer.Deserialize<FaceIdentity>(param);
return View(faceRecon);
}
[NonAction]
private ActionResult CRUD(someModel entity)
{
try
{
//you business logic here
return View(entity);
}
catch (Exception exp)
{
ModelState.AddModelError("", exp.InnerException.Message);
Response.StatusCode = 350;
return someerrohandilingactionresult(entity, actionType);
}
//Retrun appropriate message or redirect to proper action
return RedirectToAction("Index");
}
i did find something like this, helps get rid of hardcoded tempdata tags
public class AccountController : Controller
{
[HttpGet]
public ActionResult Index(IndexPresentationModel model)
{
return View(model);
}
[HttpPost]
public ActionResult Save(SaveUpdateModel model)
{
// save the information
var presentationModel = new IndexPresentationModel();
presentationModel.Message = model.Message;
return this.RedirectToAction(c => c.Index(presentationModel));
}
}

Redirect from a [HttpGet] Action To [HttpPost] Action - MVC3

I want to redirect to a [HttpPost] Action from a [HttpGet] Action in the same controller.
Is it possible?
I'm trying to not rewrite the same code for a Login, because it is a complex, and not typical logon function
This is my code:
[HttpGet]
public ActionResult Login(){
return View();
}
[HttpPost]
public ActionResult Login(LoginModel model)
{
//search user and create sesion
//...
if (registered)
{
return this.RedirectToAction("Home","Index");
}else{
return this.RedirectToAction("Home", "signIn");
}
}
[HttpGet]
public ActionResult signIn(){
return View();
}
[HttpGet]
public ActionResult signInUserModel model)
{
//Register new User
//...
if (allOk)
{
LoginModel loginModel = new LoginModel();
loginModel.User = model.User;
loginModel.password = model.password;
//next line doesn't work!!!!!
return this.RedirectToAction("Home","Login", new { model = loginModel);
}else{
//error
//...
}
}
Any help would be appreciated.
Thanks
You can return a different View from the method name
public ActionResult signInUserModel model)
{
...
return View("Login", loginModel);
}
Bit late, but I just had the same issue...
You could refactor the core login logic out from the Post method and then call that new method from both places.
e.g. Suppose you create a LoginService class to handle logging someone in. It's just a case of using that from both your actions, so no need to redirect from one action to the other
It is possible. All actions must be in the same controller.
public ActionResult Login(){
return View();
}
[HttpPost]
public ActionResult Login(LoginModel model)
{
//search user and create sesion
//...
if (registered)
{
return RedirectToAction("Index");
}
return View(model);
}
public ActionResult SignIn(){
return View();
}
[HttpPost]
public ActionResult SignIn(UserModel model)
{
//Register new User
//...
if (allOk)
{
return RedirectToAction("Login");
}
return View(model);
}

How to Upload a Photo from ASP.NET MVC to a WCF Web Service

Hi I am trying to call a WCF web service from a default ASP.NET MVC project, in order to upload a photo to the server from the ASP.NET MVC website.
My WCF web service look like this:
public void SaveImage(string fileName, byte[] photo)
{
writeByteArrayToFile(Path.Combine(#"c:\TempImg", fileName), photo);
}
public void writeByteArrayToFile(string fileName, byte[] buffer)
{
using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite))
{
fs.Write(buffer, 0, (int)buffer.Length);
}
}
In the HomeController on the project I have written this code:
using HackedTwo.ServiceReference1;
namespace HackedTwo.Controllers
{
[HandleError]
public class HomeController : Controller
{
private ServiceReference1.IService1 myWS;
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.ContentLength);
myWS.SaveImage(fileName, binData);
}
return RedirectToAction("Index");
}
}
}
Maybe I am close to getting it to work? But when I run it I get a "NullReferenceException", in the top of the code where I declare the web service, there is a green line under "myWS" and I get this message from Visual Studio "Field 'HackedTwo.Controllers.HomeController.myWS' is never assigned to, and will always have its default value null". So somehow I suspect that that might be the problem why this is not working. If that is so then my question is now: How to assign the field 'HackedTwo.Controllers.HomeController.myWS'? Or should I reference the web service in some other way into my ASP.NET MVC project?
You need to initialize this myWS variable before using it:
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
using (var myWs = new ServiceReference1.MyServiceClient())
using (var reader = new BinaryReader(file.InputStream))
{
var binData = reader.ReadBytes(file.ContentLength);
myWS.SaveImage(fileName, binData);
}
}
return RedirectToAction("Index");
}
}
or if you are using dependency injection:
[HandleError]
public class HomeController : Controller
{
private readonly IService1 _myWs;
public HomeController(IService1 myWs)
{
_myWs = myWs;
}
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
using (var reader = new BinaryReader(file.InputStream))
{
var binData = reader.ReadBytes(file.ContentLength);
myWS.SaveImage(fileName, binData);
}
}
return RedirectToAction("Index");
}
}
and then you need to configure your dependency injection to pass the proper implementation of the IService1 service contract interface in the controller constructor.

Resources