简体   繁体   English

在C#ASP.NET中将值从视图传递到视图模型

[英]Pass Value from view to viewmodel in c# ASP.NET

Thought that this might be a simple issue but I can not figure out how to pass a value from view to viewmodel in C# (EntityFramework 6 MVC ASP.NET). 以为这可能是一个简单的问题,但是我不知道如何在C#(EntityFramework 6 MVC ASP.NET)中将值从视图传递到视图模型。

Unfortunately I'm new to C# (even if not to programming, WebApps, JS etc.) - but this Razor-syntax get's me every time. 不幸的是,我是C#的新手(即使不是编程,WebApps,JS等),但这种Razor语法每次都会吸引我。 ;) ;)

I have this div and by clicking on it it would be nice to asign the person's id to a variable in my viewmodel. 我有这个div,通过单击它,将人的id分配给我的viewmodel中的变量会很好。 Then I want to use it in the Controller. 然后,我想在Controller中使用它。

Here is my view: 这是我的看法:

<div class="employee_login" id="@Html.DisplayFor(modelItem => item.Pid)" onclick="@Model.userid = @Html.DisplayFor(modelItem => item.Pid)">
    <p>@Html.DisplayFor(modelItem => item.FirstName) @Html.DisplayFor(modelItem => item.LastName) | Kennung: @Html.DisplayFor(modelItem => item.Pid)</p>
</div>

And the viewmodel: 和视图模型:

public class LoginViewModel
{
 ....

    [NonSerialized]
    public int userid;
}

Unfortunately it renders to the following HTML: 不幸的是,它呈现为以下HTML:

从浏览器渲染视图。

I read that it is good practice to pass a value from view to Controller via the viewmodel and that's exactly what MVVM-Architecture shows and wants to. 我读到,通过视图模型将值从视图传递到Controller是一个好习惯,这正是MVVM-Architecture所显示和想要的。 If it's common practice to do it via http or something else, please let me know. 如果通常通过http或其他方式进行操作,请告诉我。

Forgive me if this is a simple issue, solved in a few minutes. 如果这是一个简单的问题,请原谅,请在几分钟后解决。

Thank you and have a nice day, 谢谢你,祝你有美好的一天,

Nico 尼科

So here is a good solution for the issue (thanks to @NikhilVC). 因此,这里是解决该问题的好方法(感谢@NikhilVC)。

What I wanted was: In the Default-Login-View from the ASP.NET WebApp (MVC6 EntityFramework CodeFirst), there should be a list of all users and by clicking on one user and entering the Password the user should be logged in. But ASP.NET authenticates their users with the E-Mail-Adress. 我想要的是:在ASP.NET WebApp的默认登录视图(MVC6 EntityFramework CodeFirst)中,应该有一个所有用户的列表,并且通过单击一个用户并输入密码,应该登录该用户。但是ASP.NET使用电子邮件地址验证其用户。 Therefor a unique userid which is accessible in the view should be passed to the Controller and then searched in the db for the user to get the E-Mail. 因此,应将视图中可访问的唯一用户ID传递给Controller,然后在数据库中搜索该用户以获取电子邮件。

The View: 风景:

<div class="employee_list">
        @foreach (var item in @Model.allUsers) {
            <div class="employee_login" id="@Html.DisplayFor(modelItem => item.Pid)" data-id="@item.Pid" data-firstname="@item.FirstName" data-lastname="@item.LastName">
                <p>@Html.DisplayFor(modelItem => item.FirstName) @Html.DisplayFor(modelItem => item.LastName) | Kennung: @Html.DisplayFor(modelItem => item.Pid)</p>
            </div>
        }
    </div>
</div>
<div class="col-md-6 col-md-offset-3">
    <h4>@ViewBag.Beschreibung2</h4>
    <hr />
    <section id="loginForm">
        @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form", role = "form" })) {

            @Html.AntiForgeryToken()
            @Html.HiddenFor(@Model => @Model.userid, new { @id = "idinput", value = "0" })
            <div class="form-group">
                @Html.LabelFor(m => m.Password, new {@class = "", @id = "kennwortlabel" })
                @Html.PasswordFor(m => m.Password, new { @class = "form-control", @id = "password" })
                @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
            </div>
            <button type="submit" class="btn btn-default">Anmelden</button>
        }
    </section>
</div>

You have to create a hidden Input field which gets the userid. 您必须创建一个隐藏的Input字段来获取用户ID。 By clicking on the user this is done via jQuery: 通过单击用户,可以通过jQuery完成:

@section Scripts {
    <script>
        $(function () {
            $('body').on('click', '.employee_login', function () {
                $(this).siblings().removeClass('selected');
                $(this).addClass('selected');
                $('#idinput').val($(this).data('id'));
                $('#password').prev('#kennwortlabel').text('Kennwort für ' + $(this).data('firstname') + " " + $(this).data('lastname'));
            });
        });
    </script>
}

This is the viewmodel which connects view and Controller: 这是连接视图和Controller的viewmodel:

public class LoginViewModel {
    [EmailAddress]
    public string Email { get; set; }

    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; }

    [Display(Name = "Speichern?")]
    public bool RememberMe { get; set; }

    [NonSerialized]
    public List<ApplicationUser> allUsers;

    [Required(ErrorMessage = "Please select your name")]
    public int? userid { get; set; }
}

And the Controller: 和控制器:

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) {
        model.allUsers = db.Users.ToList();

        if (!ModelState.IsValid)
        {
            return View(model);
        }

        var user = db.Users.Where(i => i.Pid == model.userid).Single();
        if (user != null) {
            model.Email = user.Email;
        }
        else
            return View(model);

....
}

So the userid is set in the model and by clicking the submit-button, the function above is executed. 因此,在模型中设置了用户标识,然后单击提交按钮,执行了上面的功能。 It gets the user from the db where the i.Pid == model.userid and sets the E-Mail-adress in the model which is then used to authenticate the user. 它从i.Pid == model.userid的数据库中获取用户,并在模型中设置电子邮件地址,然后将其用于验证用户身份。

I am new to C# (especially with EntityFramework) but perhaps someone finds this helpful. 我是C#的新手(尤其是EntityFramework),但也许有人觉得这很有帮助。

Thanks to my supporters, 多亏了我的支持者

Nico 尼科

first you need to add one hidden field on view 首先,您需要在视图上添加一个隐藏字段

@Html.HiddenFor(model => model.userid)

and then set model value using javascript function 然后使用javascript函数设置模型值

function updateID(val)
{
    document.getElementById('userid').value = val;   
}

and call updateID function on div click 并在div上调用updateID函数

i think this will help you...... 我认为这将帮助您......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM