1

MVCとノックアウトに慣れていないので、少し助けが必要です。いくつかのJSON結果を(文字列として)コントローラーに投稿してから、コントローラーを新しいビューとアクションにRedirectToActionさせようとしています。

問題:RedirectToActionがヒットした場合でも、コントローラーは常に同じビューに戻ります。

(リダイレクトコードを通過し、最後に投稿ビューに戻ります。)「次へ」アクションを実行する必要があり、少し恥ずかしいです。

また:隠しフィールドは、投稿を行うときにIDを保存/渡すための最良の方法ですか?

見る

@model WebRole.Website.Models.Registration3Model
@{
ViewBag.Title = "Step 3: Adding Members";
}
@using (Html.BeginForm())
{

<input name="GroupID" id="GroupID" type="hidden" value="@ViewData["GroupID"]" />      
<div id="Div1">
    <div class="5grid-layout">
        <div class="row">
            <div class="8u mobileUI-main-content">
                <!-- Content -->
                <div id="content">
                    <br />
                    <!-- Article -->
                    <article class="featured">
                        <header>
                            <h2>Registration</h2>
                            <span class="byline"></span>
                        </header>
                    </article>
                    <!-- Section -->
                    <div class="5grid grid-spaced">
                        <div class="row">
                            <section class="do-6u">
                                <h2>Step 3.</h2>
                                <p>
                                    You can add members to your group/family by selecting how the members will be notified (ex. Email, Cellphone) and the address/phone # of the member.
                                </p>
                                <p />
                                    <div id='contactsList'>
                                        <table class='contactsEditor'>
                                            <tbody data-bind="foreach: contacts">
                                                <tr>
                                                    <td>
                                                        <input type="radio" value="Email" data-bind="checked: contactType" />E-mail
                                                        <input type="radio" value="Voice" data-bind="checked: contactType" />Voice
                                                        <input type="radio" value="SMS" data-bind="checked: contactType" />SMS
                                                    </td>
                                                    <td>
                                                        <input data-bind='value: contactValue' size="40" />

                                                        <a href='#' data-bind='click: $root.removeContact'>Remove</a>
                                                    </td>               
                                                </tr>
                                            </tbody>
                                        </table>
                                        <input type="hidden" data-bind='value: lastSavedJson' />
                                        <a href='#' data-bind='click: addContact'>Add </a>
                                    </div>
                                <p />
                                <p>
                                    <button name="button" value="AddNewMember" data-bind='click: save, enable: contacts().length > 0'>Invite</button>

                                    <button name="button" value="Next">Finish</button>
                                </p>
                            </section>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
}
    <script type="text/javascript">
        var initialData = [
        {
            contactValue: "",
            contactType: ""
        }
    ];

    var ContactsModel = function (contacts) {
        var self = this;
        self.contacts = ko.observableArray(ko.utils.arrayMap(contacts, function (contact) {
            return { contactValue: contact.firstName, contactType: contact.contactType };
        }));

        self.addContact = function () {
            self.contacts.push({
                contactValue: "",
                contactType: ""
            });
        };

        self.removeContact = function (contact) {
            self.contacts.remove(contact);
        };

        self.save = function () {
            self.lastSavedJson(JSON.stringify(ko.toJS(self.contacts), null, 2));
            var s = document.getElementById("GroupID").value
            $.ajax({
                url: "/Home/Add/",
                type: "POST",
                data: { jsonString: JSON.stringify(ko.toJS(self.contacts)), groupID: s },
                success: function (result) {
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    var errorMessage = '';
                    $('#message').html(jqXHR.responseText);
                }
            });

        }; 


        self.lastSavedJson = ko.observable("")
    };

    ko.applyBindings(new ContactsModel(initialData));


</script>

モデル:

public class Registration3Model
{
    public string GroupID { get; set; }

    // Success Message
    public string SuccessMessage { get; set; }

    public string jsonString { get; set; }
}

public class Registration4Model
{
    public string GroupID { get; set; }

    public Group SelectedGroup { get; set; }

    public Person Owner { get; set; }

    public List<ContactInfo> GroupContacts { get; set; }

    // Success Message
    public string SuccessMessage { get; set; }
}

コントローラ:

public class HomeController : Controller
{
    public class JsonCatch
    {
        public string groupID { get; set; }
        public string contactType { get; set; }
        public string contactValue { get; set; }
    }


    [AllowAnonymous]
    public ActionResult Registration3(Registration3Model model)
    {
        ViewData["GroupID"] = model.GroupID;
        return View("Registration3",  model);
    }

    [HttpPost]
    [ActionName("Add")]
    [AllowAnonymous]
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Add(string jsonString, string GroupID)
    {

    string s =GroupID;

        List<JsonCatch> j = JsonConvert.DeserializeObject<List<JsonCatch>>(jsonString);
        foreach (JsonCatch c in j)
        { 
            if (s != "")
            {

                // for member 1
                // 1. Add Person
                Person p = new Person();
                p.LastName = "";
                p.FirstName = "";
                p.PersonID = Guid.NewGuid();
                p.RowKey = p.PersonID.ToString();
                p.PartitionKey = "";
                p.Image = string.Format("../../Assets/Images/People/pic{0}.png", new Random().Next(1, 12));
                this.GetContext().InsertPerson(p);

                // 2. Add GroupMember
                GroupMember gm = new GroupMember();
                gm.RowKey = p.RowKey.ToString();
                gm.PartitionKey = s;
                gm.GroupMemberID = Guid.NewGuid();
                gm.TrustLevel = "Readonly";
                this.GetContext().InsertGroupMember(gm);

                // 3. Add ContactInfo
                ContactInfo ci = new ContactInfo();
                ci.PartitionKey = p.RowKey;
                ci.ContactInfoID = Guid.NewGuid();
                ci.RowKey = ci.ContactInfoID.ToString();
                ci.Type = c.contactType;
                ci.Value = c.contactValue;
                ci.UseToNotify = true;
                this.GetContext().InsertContactInfo(ci);

                // 4. Add Notification
                Notification n = new Notification();
                n.PartitionKey = "Invitation";
                n.NotificationID = Guid.NewGuid();
                n.RowKey = n.NotificationID.ToString();
                n.ContactType = c.contactType;
                n.ContactInfoValue = c.contactValue;
                n.NotificationType = "Invitation";
                n.PersonRowKey = p.RowKey;
                n.GroupRowKey = s;
                this.GetContext().InsertNotification(n);
            }
            }
        return View("Registration4", new { GroupID = s });
    }

            [AllowAnonymous]
    public ActionResult Registration4(Registration4Model model)
    {
        model.SelectedGroup = this.GetContext().GetGroup(model.GroupID);
        model.GroupContacts = model.SelectedGroup.GetContactInfoes(this.GetContext());
        model.Owner = model.SelectedGroup.GetOwner(this.GetContext());

        return View(model);
    }

            [HttpPost]
    [AllowAnonymous]
    [AcceptVerbs(HttpVerbs.Post)]
    [ActionName("Registration3")]
    [AcceptParameter(Name = "button", Value = "Next")]
    public ActionResult Registration3_Next(Registration4Model model)
    {
        return RedirectToAction("Registration4", new { GroupID = model.GroupID });
    }


    [HttpPost]
    [AllowAnonymous]
    [AcceptVerbs(HttpVerbs.Post)]
    [ActionName("Registration4")]
    [AcceptParameter(Name = "button", Value = "Continue")]
    public ActionResult Registration4_Continue(Registration4Model model)
    {
        return Redirect("~/AnotherWebsite.aspx");
    }

    #endregion
}

public class AcceptParameterAttribute : ActionMethodSelectorAttribute
{
    public string Name { get; set; }
    public string Value { get; set; }

    public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
    {
        var req = controllerContext.RequestContext.HttpContext.Request;
        return req.Form[this.Name] == this.Value;
    }
}
4

1 に答える 1

1

window.location = url問題は、Ajaxを使用してAddメソッドを呼び出しているため、を使用して新しいビューに変更する必要があることです。

試してみる必要があるのは、GroupIdを含むJsonResultを返し、Ajax呼び出しの使用と変更のビューの成功部分を返すことです。window.location

これをモデルの外に追加します

 var newUrl="@Url.Action("Registration","Home")";

次にモデル内

 self.save = function () {
        self.lastSavedJson(JSON.stringify(ko.toJS(self.contacts), null, 2));
        var s = document.getElementById("GroupID").value
        $.ajax({
            url: "/Home/Add/",
            type: "POST",
            data: { jsonString: JSON.stringify(ko.toJS(self.contacts)), groupID: s },
            success: function (result) {
Code Change ----->  window.location=newUrl+"/"+result;
            },
            error: function (jqXHR, textStatus, errorThrown) {
                var errorMessage = '';
                $('#message').html(jqXHR.responseText);
            }
        });

    }; 

コントローラがIDだけを返すと仮定しています。それがうまくいくことを願っています。

于 2012-10-16T01:59:10.843 に答える